題目:
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.
代碼如下:
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(m==n)return head;
int i=1;
if(m==1)
{
ListNode *head1=head;
while(i<n)
{
ListNode *tmp=head1->next;
head1->next=tmp->next;
tmp->next=head;
head=tmp;
i++;
}
}
else
{
ListNode *head1=head;
while(i<m-1)
{
head1=head1->next;
i++;
}
ListNode *head2=head1->next;
while(i<n-1)
{
ListNode *tmp=head2->next;
head2->next=tmp->next;
tmp->next=head1->next;
head1->next=tmp;
i++;
}
}
return head;
}