题目:
Reverse a linked list from position m to n.
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
Example
Given 1->2->3->4->5->NULL
, m = 2
and n = 4
, return 1->4->3->2->5->NULL
.
题解:
Solution 1 ()
class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode* first = new ListNode(-1); first->next = head; ListNode* prev = first; for (int i = 0; i < m - 1; ++i) { prev = prev->next; } ListNode* cur = prev->next; for (int i = 0; i < n - m; ++i) { ListNode* tmp = cur->next; cur->next = tmp->next; tmp->next = prev->next; prev->next = tmp; } return first->next; } };