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.
Big early in the morning to be linked to the list of abuse cry Ah, looked at others, the amount can be so simple, sure enough brain still turn to, in fact, is a very common topic, the code is very simple, completely without comments can also:
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)returnNULL; -ListNode * p =head; - intI, J; the for(i =1; I < m; ++i) { -p = p->Next; - } -ListNode * q =p; + for(i = m; i < n; + +)i) { - for(j = i; J < N; + +)K) { +Q = q->Next; A } atSwap (P->val, q->val); -n--; -p = p->Next; -Q =p; - } - returnhead; in } -};
Pay attention to the swap, the swap is very clever.
After seeing a great God written out, also very simple, paste out to learn one:
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 //Start Typing your/C + + solution below - //Do not write int main () function - if(Head = =NULL) the returnNULL; - -ListNode *q =NULL; -ListNode *p =head; + for(inti =0; I < M-1; i++) - { +Q =p; Ap = p->Next; at } - -ListNode *end =p; -ListNode *ppre =p; -p = p->Next; - for(inti = m +1; I <= N; i++) in { -ListNode *pnext = p->Next; to +P->next =Ppre; -Ppre =p; thep =Pnext; * } $ Panax NotoginsengEnd->next =p; - if(q) theQ->next =Ppre; + Else AHead =Ppre; the + returnhead; - } $};
Alas, often encountered linked to the list of brain can not turn, this is still more practice AH.
Leetcode oj:reverse Linked List II (reverse link List II)