双循环链表之分离

 要求:

把a1,a2,a3,a4,....an分离成

a1,a3,a5,....an,..a4,a2;

代码如下:

//双循环链表
//带头结点的循环链表
#include <iostream>
using namespace std;
typedef int ElemType;
//结点类型定义
typedef struct DoubleListNode 
{
	ElemType data;
	DoubleListNode *prior;
	DoubleListNode *next;
}DoubleListNode;

DoubleListNode* CreateList(DoubleListNode *&root,int n)
{
	DoubleListNode *last=new DoubleListNode;
	last->prior=last->next=NULL;
	last=root;
	cout<<"请输入结点的信息"<<endl;
	int i;
	ElemType temp;
	for(i=0;i<n;++i)
	{
		cin>>temp;
		DoubleListNode *newnode=new DoubleListNode;
		newnode->data=temp;
		newnode->prior=newnode->next=NULL;
		newnode->next=last->next;
		last->next=newnode;
		newnode->prior=last;
		root->prior=newnode;
		last=newnode;
	}
	return root;
}

void Display(DoubleListNode *root)
{
	DoubleListNode *current=root->next;
	DoubleListNode *temp=new DoubleListNode;
	while (current!=root)
	{
		temp=current;
		cout<<current->data<<" "<<"它的前驱结点是";
		if(temp->prior==root)
			cout<<temp->prior->prior->data;
		else
		{
			cout<<temp->prior->data;
		}
		cout<<"  "<<"它的后继结点是";
		if(temp->next==root)
			cout<<temp->next->next->data<<endl;
		else
		{
			cout<<temp->next->data<<endl;
		}
		current=current->next;
	}
}

void Separate(DoubleListNode *&root)
{
	DoubleListNode *current=new DoubleListNode;
	current->prior=current->next=NULL;
	current=root->next;
	while (current->next!=root&¤t->next->next!=root)
	{
		current->next=current->next->next;            //跳过偶数结点
		current=current->next;
	}
	if(current->next==root)  current->next=root->prior->prior;      //如果原数组最后一位是奇数,则连接最后一个偶数
	else if(current->next->next==root)      //最后一位是偶数,则连接次偶数
	{
		current->next=root->prior;
	}
	current=current->next;       //此时current定位为最后一个结点,现在开始连偶数点
	while (current->prior->prior!=root)
	{
		current->next=current->prior->prior;
		current=current->next;
	}
	current->next=root;
	for(current=root;current->next!=root;current=current->next)
		current->next->prior=current;
	root->prior=current;
}
int main()
{
	DoubleListNode *root=new DoubleListNode;
	root->prior=root->next=root;
	int n;
	cout<<"创建几个结点的双循环链表"<<endl;
	cin>>n;
	root=CreateList(root,n);
	cout<<"链表创建成功"<<endl;
	Display(root);
	cout<<endl;
	Separate(root);
	cout<<"分离后的链表"<<endl;
	Display(root);
	system("pause");
	return 0;
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值