Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
这道题我遍历了两遍链表,第一遍遍历记录开始和结束的节点,存储节点对应值;第二遍遍历之前先将存储的值反转,然后分别赋值给每个节点。
/**
* 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) {
vector<int> tem;
int count=1;
ListNode* ptr = head;
ListNode* start = head;
while(count!=m) {
ptr=ptr->next;
count++;
}
start = ptr;
while(count!=n+1){
tem.push_back(ptr->val);
ptr=ptr->next;
count++;
}
reverse(tem.begin(), tem.end());
count = m;
ptr = start;
int i=0;
while(count!=n+1){
ptr->val = tem[i];
i++;
count++;
ptr = ptr->next;
}
return head;
}
};