题目描述:(链接)
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.
解题思路:
头插法
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(-1); 13 dummy.next = head; 14 ListNode *prev = &dummy; 15 for (int i = 0; i < m - 1; ++i) { 16 prev = prev->next; 17 } 18 19 ListNode *head2 = prev; 20 prev = head2->next; 21 ListNode *current = prev->next; 22 for (int i = m; i < n; ++i) { 23 prev->next = current->next; 24 current->next = head2->next; 25 head2->next = current; 26 current = prev->next; 27 } 28 29 return dummy.next; 30 } 31 };