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) {
if(m==n)
return head;
ListNode* prev=NULL;
ListNode* curr=head;
ListNode* next=NULL;
// the head node is at position 1
int pos=1;
// find the node at position m
while(pos<m)
{
prev = curr;
curr = curr->next;
pos++;
}
ListNode* old_prev = prev;
ListNode* old_curr = curr;
// start with the node at position m+1
prev = curr;
curr = curr->next;
next = curr->next;
pos++;
while(pos<=n)
{
curr->next = prev;
prev = curr;
curr = next;
if(curr)
next = curr->next;
pos++;
}
if(m>1)
old_prev->next = prev;
old_curr->next = curr;
if(m>1)
return head;
else
return prev;
}
};
下面是一个更简洁的代码:
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* h=head;
for (int i=0;i<n-m;i++){
int k1=m+i;
int k2=n-i;
if (k1>=k2){return head;}
ListNode* p = h;
ListNode* q = h;
while (k1-1>0){p=p->next;k1--;}
while (k2-1>0){q=q->next;k2--;}
int tmp=p->val;
p->val=q->val;
q->val=tmp;
}
return head;
}
};