zoukankan      html  css  js  c++  java
  • Reverse Linked List II

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    Discuss

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
     ListNode *reverseList(ListNode *root)
        {
            if(!root||!root->next)
                return root;
            ListNode *p,*q,*tem;
            p = root;
            q = NULL;
            while(p)
            {
                if(!q)
                {
                    p = p->next;
                    q = root;
                    q->next = NULL;
                    continue;
                }
              tem = p;
              p   = p->next;
              tem->next = q;
              q = tem;
            }
            return q;
        }
        
        ListNode *reverseBetween(ListNode *head, int m, int n)
        {
            if(NULL==head||NULL==head->next||m==n)
                return head;
            ListNode *mp = head; // the point to the head of list
            ListNode *np = head; // the tail of list
            ListNode *mp1;       // the head of list 
            ListNode *np1;
            ListNode *newhead;
           
             while(n!=1&&n--)
                np = np->next;
            if(m==1&&NULL==np->next)
               return reverseList(head);
              
            if(m==1&&NULL!=np->next)
            {
                np1 = np->next;
                np->next = NULL;
                newhead = reverseList(head);
                head->next = np1;
                return newhead;
            }
            
                
            while(m!=2&&m--)
                mp = mp->next;
            
            mp1 = mp->next;
            np1 = np->next;
            np->next = NULL;
            reverseList(mp1);
          
                      
            mp->next = np;
            mp1->next = np1;
            return head;
               
            
        }
    };

    注意几点:
    1. 调用reverseList()时, 尾结点要置NULL, 否则不符合调用规则,程序会超时
    2. 考虑情况较多, 均分别处理
    ~m=n
    ~m=1, n<len
    ~m=1, n = len
    ~n=len
    ~1<m<n<len

    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    vue 如何点击按钮返回上一页
    vue遍历数组和对象的方法以及他们之间的区别
    css隐藏滚动条
    DOM编程以及domReady加载的几种方式
    修改默认滚动条默认样式
    面试题集锦
    正则表达式
    闭包及应用以及顺序处理ajax请求
    实现自己的(模仿jquery)toggle函数
    Asp.Net与SEO Viewstate优化终极解决方案
  • 原文地址:https://www.cnblogs.com/vintion/p/4116961.html
Copyright © 2011-2022 走看看