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 class Solution { 10 public: 11 ListNode* reverseBetween(ListNode* head, int m, int n) { 12 if(!head){ 13 return head; 14 } 15 ListNode* newHead = new ListNode(-1); 16 newHead->next = head; 17 18 19 //因為m 可能為1,n為2,此時需要三個結點才能完成轉換, 20 //所以pNode設為newHead, 21 //這樣newHead結點,第一個,第二個結點就可以完成轉換 22 ListNode* pNode = newHead; 23 24 for(int i = 1; i < m ; i++){ 25 pNode = pNode->next; 26 } 27 28 ListNode* pm = pNode->next;; 29 30 for(int i = m ; i < n; i++){ 31 ListNode* n = pm->next; 32 pm->next = n->next; 33 n->next = pNode->next; 34 pNode->next = n; 35 } 36 return newHead->next; 37 } 38 };