1.定义三的指针变量*p、*q、*t,p指向原链表的头结点head1,新建另一个头结点head2,q指向head2,t指向head1的next结点,两个头结点的next都设为空。
2.按照条件分配t指向的结点,如果将这个结点连接到head1的链表中,(1)让p的next指向t(2)p和t都向后移,既p指向p的next,t指向t的next。(3)再让p的next为空。
//链表拆分
#include <iostream>
#include<stdlib.h>
using namespace std;
struct node
{
int x;
struct node *next;
};
//顺序建表
struct node *creatListShun(int lenth)
{
struct node *head,*t,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
t=head;
for(i=0; i<lenth; i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->x=i;
p->next=NULL;
t->next=p;
t=p;
}
return head;
}
struct node * chaifen(struct node *head1)
{
struct node *p,*q,*t,*head2;
t=head1->next;
head1->next=NULL;
head2=(struct node *)malloc(sizeof(struct node));
head2->next=NULL;
p=head1;
q=head2;
while(t)
{
if(t->x%2==0)
{
p->next=t;
t=t->next;
p=p->next;
p->next=NULL;
}
else
{
q->next=t;
t=t->next;
q=q->next;
q->next=NULL;
}
}
return head2;
};
int main()
{
struct node *head1,*t1,*head2,*t2;
head1=creatListShun(10);//顺序建链表
t1=head1->next;
cout<<"顺序建链表 :";
while(t1!=NULL)
{
cout<<t1->x<<" ";
t1=t1->next;
}
cout<<endl;
//链表拆分
cout<<"链表拆分"<<endl;
head2=chaifen(head1);
t1=head1->next;
while(t1)
{
cout<<t1->x<<" ";
t1=t1->next;
}
cout<<endl;
t2=head2->next;
while(t2)
{
cout<<t2->x<<" ";
t2=t2->next;
}
cout<<endl;
return 0;
}