链表——单链表的拆分

摘要:单链表的拆分使用到的方法和单链表的逆置相似,下面上代码
单链表拆分的思路
1、为要拆分的子链表建立属于他们的表头
2、设立工作指针根据要求从原表中选择性插入子链

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    struct node *head,*p,*q,*tail;
    int n,i;
    scanf("%d",&n);
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    for(i=1; i<=n; i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    struct node *head1,*head2,*tail1,*tail2;//这里其实多建立了一个表头
    //原表的表头已经空出来了,这里也可也只设置一套就可以
    head1=(struct node*)malloc(sizeof(struct node));
    head2=(struct node*)malloc(sizeof(struct node));
    head1->next=NULL;
    head2->next=NULL;
    p=head->next;
    q=p->next;
    tail1=head1;
    tail2=head2;
    int num1,num2;
    num1=num2=0;
    while(p)
    {
        if(p->data%2==0)
        {
            p->next=NULL;//这里还是要让他指向NULL,不然建立完的链表在输出又会出问题
            tail2->next=p;
            tail2=p;
            num2++;
        }
        else
        {
            p->next=NULL;
            tail1->next=p;
            tail1=p;
            num1++;
        }
        p=q;
        if(q)
            q=q->next;
    }
    printf("%d %d\n",num2,num1);
    p=head2->next;
    while(p)
    {
        if(p->next)
            printf("%d ",p->data);
        else
            printf("%d\n",p->data);
        p=p->next;
    }
    p=head1->next;
    while(p)
    {
        if(p->next)
            printf("%d ",p->data);
        else
            printf("%d\n",p->data);
        p=p->next;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值