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.
思路:也没什么特别的,就是要注意考虑边界情况。
- ListNode *reverseBetween(ListNode *head, int m, int n) {
- if(!head) return NULL;
- if(m == n) return head;
- ListNode dummy(0);
- dummy.next = head;
- ListNode *prev = &dummy;
- ListNode *first = head;
- #first's index will be from m to n-1
- int k = 0;
- while(k++ < m-1) prev = prev->next;
- first = prev->next;
- ListNode *front = first, *back = first->next;
- for(k = 0; k < n - m; k++){
- ListNode *temp = back->next;
- back->next = front;
- front = back;
- back = temp;
- }
- prev->next = front;
- first->next = back;
- return dummy.next;
- }
No comments:
Post a Comment