题目描述:
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.
解题思路:
给定一个链表,要求反转从第m个节点到第n个节点的子链表,要求一次完成扫描完成,且不能用额外的空间
m,n满足 1<=m<=n<=链表长度。
m,n满足 1<=m<=n<=链表长度。
先确定要反转的子链表的首尾节点,把子链表拎出来单独做反转。待反转完成之后链回到原来的链表中。
在程序中,用p表示翻转之前的那个节点,即第m-1个节点,用s表示n+1个节点,用pp表示翻转子序列的尾部节点,即第n个节点。翻转之后,p指向翻转之后的子序列头,子序列尾pp指向后面未翻转节点s。
代码如下:
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;
}
运行结果如下图: