码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List II

时间:2015-05-05 14:34:24      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:

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;
}


运行结果如下图:
技术分享


Reverse Linked List II

标签:

原文地址:http://blog.csdn.net/sinat_24520925/article/details/45500679

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!