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.
思路:
用四个指针分别记录第m-1,m, n, n+1个节点,然后把第m到n个节点之间的node的next指向前一个node。注意一些特殊情况的判断。
代码:
1 ListNode *reverseBetween(ListNode *head, int m, int n) { 2 // Note: The Solution object is instantiated only once and is reused by each test case. 3 if(head == NULL) 4 return NULL; 5 if(m == n) 6 return head; 7 ListNode *msub1, *mp, *np, *nadd1, *last, *cur, *nextp, *tmp; 8 if(m == 1) 9 msub1 = NULL; 10 int index = 1; 11 tmp = head; 12 while(tmp){ 13 if(index == m-1){ 14 msub1 = tmp; 15 } 16 if(index == m){ 17 mp = tmp; 18 break; 19 } 20 tmp = tmp->next; 21 index++; 22 } 23 if(mp == NULL || mp->next == NULL) 24 return head; 25 last = mp; 26 cur = mp->next; 27 if(cur == NULL) 28 return head; 29 nextp = cur->next; 30 index = m+1; 31 while(index <= n){ 32 if(index == n){ 33 np = cur; 34 } 35 cur->next = last; 36 last = cur; 37 cur = nextp; 38 if(nextp == NULL) 39 break; 40 nextp = nextp->next; 41 index++; 42 } 43 nadd1 = cur; 44 if(msub1) 45 msub1->next = np; 46 else 47 head = np; 48 mp->next = nadd1; 49 return head; 50 }