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.
Subscribe to see which companies asked this question.
本题要求如上,我的想法是在上一题的解法基础上解答。生成一个头结点,然后依次遍历计数,遍历的同时逆置。最终需要判定n==m时的边界条件,直接返回head。
/**
* 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) {
if(n==m) return head;
ListNode* newhead=new ListNode(0);
newhead->next=head;
ListNode* pre=newhead;
int count=1;
while(count<n){
while(count<m){
pre=pre->next;
head=head->next;
++count;
}
ListNode* temp=head->next->next;
head->next->next=pre->next;
pre->next=head->next;
head->next=temp;
++count;
}
return newhead->next;
}
};