单链表的链表拆分

来源:互联网 发布:菜鸟网络cfo 编辑:程序博客网 时间:2024/05/22 04:28

1.定义三的指针变量*p*q*tp指向原链表的头结点head1,新建另一个头结点head2q指向head2t指向head1next结点,两个头结点的next都设为空。

2.按照条件分配t指向的结点,如果将这个结点连接到head1的链表中,(1)pnext指向t(2)pt都向后移,既p指向pnextt指向tnext(3)再让pnext为空。

//链表拆分#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;}


0 0
原创粉丝点击