Leetcode-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->NULL
, m = 2 and n = 4,
Return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤length of list.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Reversebetween (listnode* head,intMintN) { A if(head = = NULL | | m==n)returnhead; -listnode* TP =head; -listnode* h =head; thelistnode* TAIL,*PREV,*CUR,*NXT, *before; - intCount =0; - -Prev =NULL; +Cur =head; -NXT = head->Next; + for(intI=1; i<m;i++{//Find the first node that needs to be reversed. Prev is the precursor node, cur is the current node, and NXT is the successor node APrev =cur; atCur =NXT; -NXT = nxt->Next; - } -Before =prev;//The node before the reversed part (possibly an empty node, that means the inverse from the first node) -Tail =cur;//Reverse part of the final tail node - for(inti=m;i<n;i++) {//start the reverse until the last node that needs to be reversed is stopped (the last node that needs to be reversed is processed separately) inCur->next =prev; -Prev =cur; toCur =NXT; +NXT =nxt->Next; - } theCur->next =prev;//Now Cur is pointing to the last node that needs to be reversed * if(Before = =NULL) {//If before points to an empty node, it indicates that the head node needs to be changed. $Head =cur;Panax Notoginseng } - Else{//otherwise will "That node before the part that was reversed"Next points to the current node (i.e. the last node that needs to be reversed)
theBefore->next =Cur
+ }
ATail->next =NXT;//The last node of the reversed part to connect to the following part of the list
the returnHead;
+ }
-};
Leetcode-reverse Linked List II