题目:
Reverse a linked list from position m to n. Do it in-place and in one-pass. (Medium)
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)用来链接链表。
使用dummy node,统一处理当链表头也被翻转的情况。
代码:
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 ListNode dummy(0); 13 dummy.next = head; 14 head = &dummy; 15 ListNode* temp = head; 16 for (int i = 1; i < m; ++i) { 17 temp = temp -> next; 18 } 19 ListNode* reverseEnd = nullptr; 20 ListNode* reverseBegin = temp -> next; 21 ListNode* p = reverseBegin; 22 for (int i = 0; i <= n - m; ++i) { 23 ListNode* next = p -> next; 24 p -> next = reverseEnd; 25 reverseEnd = p; 26 p = next; 27 } 28 temp -> next = reverseEnd; 29 reverseBegin -> next = p; 30 return dummy.next; 31 } 32 };