您的位置:首页 > 其它

链表拆分

2016-07-26 19:08 274 查看

题目描述

输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。

输入

第一行输入整数N;;

第二行依次输入N个整数。

输出

第一行分别输出偶数链表与奇数链表的元素个数; 

第二行依次输出偶数子链表的所有数据;

第三行依次输出奇数子链表的所有数据。
#include <stdio.h>

#include <stdlib.h>

struct node

{

    int data;

    struct node*next;

};

int main()

{

    int n,i,x=0,y=0;

    struct node*head1,*head2,*p,*q;

    scanf("%d",&n);

    head1=(struct node*)malloc(sizeof(struct node));

    head1->next=NULL;

    for(i=0; i<=n-1; i++)

    {

        p=(struct node*)malloc(sizeof(struct node));

        scanf("%d",&p->data);

        p->next=NULL;

        p->next=head1->next;

        head1->next=p;

    }

    p=head1->next;

    q=p->next;

    head1->next=NULL;

    head2=(struct node*)malloc(sizeof(struct node));

    head2->next=NULL;

    while(p!=NULL)

    {

        if(p->data%2==0)

        {

            x++;

            p->next=head1->next;

            head1->next=p;

        }

        else

        {

            y++;

            p->next=head2->next;

            head2->next=p;

        }

        p=q;

        if(q!=NULL)

            q=q->next;

    }

    printf("%d %d\n",x,y);

    p=head1->next;

    while(p!=NULL)

    {

        if(p->next!=NULL)

            printf("%d ",p->data);

        else printf("%d\n",p->data);

        p=p->next;

    }

    p=head2->next;

    while(p!=NULL)

    {

        if(p->next!=NULL)

            printf("%d ",p->data);

        else printf("%d\n",p->data);

        p=p->next;

    }

    return 0;

}

分开head1和head2 ,p和q在一条链上谁符合要求就加在哪条链后
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: