Reverse Linked List II

来源:互联网 发布:如何摆脱抑郁症知乎 编辑:程序博客网 时间:2024/06/18 13:26

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.

解析:

找到前面两个节点,每次新的节点插入到头结点后面

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
    
       if (head==NULL) return NULL;
       if (m==n) return head;
       ListNode* nextp;
       ListNode* prehead=new ListNode(0);
       prehead->next=head;
       ListNode* cur=new ListNode(0);
       ListNode* newhead=new ListNode(0);
       newhead->next=cur;
       nextp=prehead;
       ListNode* preh=prehead;
       for (int i=0; i<m; i++)
       {
           preh=nextp;
           nextp=nextp->next;
       }
       
       for (int i=m-1; i<n; i++)
       {
           ListNode* temp=nextp;
           nextp=nextp->next;
           temp->next=newhead->next;
           newhead->next=temp;
           if (i==(m-1))
           {
               cur=temp;
           }
           
       }
       preh->next=newhead->next;
       cur->next=nextp;
       return prehead->next;
       
        
        
        
        
    }
};