#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
}
[数据结构] 单向链表拆分成两个循环链表
最新推荐文章于 2023-02-04 17:18:40 发布