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.
注意题目 Do it in-place and in one-pass.
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 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 int count = 1; 15 ListNode * tmp = head; 16 ListNode * subListHead; 17 ListNode * subListTail; 18 ListNode * temp; 19 ListNode * pre = NULL; 20 ListNode * breakpoint1; 21 ListNode * breakpoint2; 22 while(count <= n) 23 { 24 temp = tmp->next; 25 if(count == m) 26 { 27 subListTail = tmp; 28 breakpoint1 = pre; 29 } 30 if(count == n) 31 { 32 subListHead = tmp; 33 breakpoint2 = tmp->next; 34 } 35 if(count > m) 36 { 37 tmp->next = pre; 38 } 39 pre = tmp; 40 tmp = temp; 41 count++; 42 } 43 ListNode * newHead; 44 if(breakpoint1 == NULL) 45 { 46 newHead = subListHead; 47 } 48 else 49 { 50 newHead = head; 51 breakpoint1->next = subListHead; 52 } 53 subListTail->next = breakpoint2; 54 return newHead; 55 } 56 };

浙公网安备 33010602011771号