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.
[Solution]
1 ListNode *reverseBetween(ListNode *head, int m, int n) 2 { 3 ListNode dummy = ListNode(INT_MIN), *p, *q, *r; 4 dummy.next = head; 5 if (head == NULL) 6 return NULL; 7 8 p = q = &dummy; 9 for (int i = 1; i <= n - m; i++) 10 p = p->next; 11 for (int i = 1; i < m; i++) 12 { 13 p = p->next; 14 q = q->next; 15 } 16 p = p->next; 17 r = p->next; 18 p->next = NULL; 19 20 p = q->next; 21 q->next = reverse(p); 22 p->next = r; 23 24 return dummy.next; 25 } 26 27 ListNode *reverse(ListNode *head) 28 { 29 ListNode *p = NULL, *q, *r; 30 31 q = head; 32 if (q == NULL) 33 return NULL; 34 r = q->next; 35 while (r != NULL) 36 { 37 q->next = p; 38 p = q; 39 q = r; 40 r = r->next; 41 } 42 q->next = p; 43 44 return q; 45 }
时间: 2024-10-29 19:09:56