Reverse Linked List II

题目描述:

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解题思路:

给定一个链表,要求反转从第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;
}


运行结果如下图:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值