[数据结构] 单向链表拆分成两个循环链表

#include <iostream>
using namespace std;
struct node 
{
	int data;
	struct node *next;
} ;
struct node *CreatNode();
void DisplayNode(struct node *head);
void SeparateNode(struct node *head,struct node *&p,struct node *&q);
int main()
{
	cout<<"链表:"<<endl;
	struct node *p1;
	struct node *p2,*p3;
	p1=CreatNode();
	cout<<"链表:"<<endl;
	
	DisplayNode(p1);
	cout<<endl;
	
	SeparateNode(p1,p2,p3);
	DisplayNode(p2);
	DisplayNode(p3);
	struct node *r1,*r2;
	r1 = p2;
	r2 = p3;
	while(p2->next!=NULL)
	{
		p2 = p2->next;
	}
	p2->next = r1;
	while(p3->next!=NULL)
	{
		p3 = p3->next;
	}
	p3->next = r2;
	DisplayNode(p2);
	DisplayNode(p3);
	return 0;
} 

struct node *CreatNode()
{
	node *head;
	node *p,*q;
	int data;
	head = new struct node;
	head->next = NULL;
	cin >> data;
	while(data!=0) 
	{
		p = new struct node;
		p->data = data;
		q = head;
		while(q->next!=NULL)
		{
			q=q->next;
		}
		q->next = p;
		p->next = NULL;
		cin >> data; 
	}
	return head;
}

void DisplayNode(struct node *head)
{
	int i=1;
	if(head==NULL)
	{
		cout<<"Not Exist!\n"<<endl;
		return ;
	}
	cout<<"序号     数据"<<endl; 
	struct node *p;
	p=head->next;
	while((p!=NULL)&&(i<10))//默认输出10位数据的循环链表 
	{
		cout<<i<<"         "<<p->data<<endl;
	    p=p->next;
	    i++;
	}
	head->data = i-1; 
	cout<<endl;
}

void SeparateNode(struct node *head,struct node *&p,struct node *&q)
{
     int flag=0;//结点号标记
     node *p1 = head->next;//用于遍历链表head
     node *r1,*r2,*x,*y;
 
     p = new node;
     q = new node;
     r1=p;
     r2=q;
     p->next = q->next =NULL;
 
    while(p1)
    {
       flag++;
       if(flag%2 == 1)
       {
            x=new node;
            x->data = p1->data;
            r1->next = x;
            r1 = x;
        }
 
        else
        {
            y = new node;
            y->data = p1->data;
            r2->next = y;
            r2 = y;
        }
        p1=p1->next;//遍历head 
     }
 
     r1->next = r2->next = NULL;//初始化r1,r2 
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值