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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值