单链表的链表拆分

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值