92. Reverse Linked List II (List)
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode* fakeHead = new ListNode(0); fakeHead->next = head; //find the last element of first section ListNode* rHead = fakeHead; int i = 0; for(; i < m-1; i++){ rHead = rHead->next; } //m-n element will be reversed ListNode* secondHead = rHead->next; //head of the original second section ListNode* current = secondHead->next; //current node to reverse ListNode* tmp; for(i = m; i < n; i++){ //reverse from m to n tmp = rHead->next; rHead->next = current; secondHead->next = current->next; current->next = tmp; current = secondHead->next; } //keep the third section and return return fakeHead->next; } };