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(head==NULL||head->next==NULL) return head;
if(m==n) return head;
ListNode *p=head,*p1=head,*p2,*p3,*s,*pp;
p2=p1->next;
for(int i=1;i<n;i++)
{
if(i==m-1) p=p1;
if(i<m)
{
p1=p2;
p2=p1->next;
}
else
{
if(i==m)
{
pp=p1;
}
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
if(i==n-1) s=p2;
}
if(m==1)
{
head->next=s;
head=p1;
}
else
{
p->next=p1;
pp->next=s;
}
return head;
}完整代码如下:#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode * CreatList();
ListNode* reverseBetween(ListNode* head, int m, int n);
void main()
{
ListNode *head=CreatList();
ListNode *p=head;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
ListNode *head1=reverseBetween(head, 2, 4);
p=head1;
while(p)
{
cout<<p->val<<" ";
p=p->next;
}
}
ListNode * CreatList()
{
ListNode *head=(ListNode*)malloc(sizeof(ListNode));
ListNode *p,*s;
p=head;
int x,cycle=1;
while(cycle)
{
cin>>x;
if (x!=0)
{
s=(ListNode*)malloc(sizeof(ListNode));
s->val=x;
p->next=s;
p=s;
}
else cycle=0;
}
head=head->next;
p->next=NULL;
return head;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(head==NULL||head->next==NULL) return head;
if(m==n) return head;
ListNode *p=head,*p1=head,*p2,*p3,*s,*pp;
p2=p1->next;
for(int i=1;i<n;i++)
{
if(i==m-1) p=p1;
if(i<m)
{
p1=p2;
p2=p1->next;
}
else
{
if(i==m)
{
pp=p1;
}
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
if(i==n-1) s=p2;
}
if(m==1)
{
head->next=s;
head=p1;
}
else
{
p->next=p1;
pp->next=s;
}
return head;
}
原文:http://blog.csdn.net/sinat_24520925/article/details/45500679