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

    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    Macbook键盘的使用基础技巧
    JSTL详解
    为了理想,因为爱情-开课第一天有感(鸡汤向)
    HK游记 Day2迪斯尼(下)
    MP20 MBO issue summary
    音频测量加权
    有没有降噪
    信源编码信源译码和信道编码和译码和加密和解密数字调制和解调和同步
    gcc
    数据挖掘|统计的艺术
  • 原文地址:https://www.cnblogs.com/vintion/p/4116961.html
Copyright © 2011-2022 走看看