G - 数据结构实验之链表五:单链表的拆分

此代码实现了一个功能,从输入的整数顺序构建的单链表中,将所有偶数和奇数分别拆分成两个子链表,并保持原链表的相对次序。程序首先读取整数数量,然后创建链表,接着拆分链表,最后输出两个子链表的元素个数及所有数据。
摘要由CSDN通过智能技术生成

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

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

Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。

Sample

Input 
10
1 3 22 8 15 999 9 44 6 1001
Output 
4 6
22 8 44 6 
1 3 15 999 9 1001
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <math.h>
using namespace std;
//定义结构体
typedef struct node
{
    int data;
    struct node *next;
} Node;
//创建链表
Node *creat(int n)
{
    Node *tail,*p,*head;
    head=(Node *)malloc(sizeof(Node));
    head->next=NULL;
    tail=head;
    for(int i=1; i<=n; i++)
    {
        p=(Node *)malloc(sizeof(Node));
        scanf("%d",&p->data);
        tail->next=p;
        tail=p;
        p->next=NULL;
    }
    return head;
}
//输出链表
void ouput(Node *head)
{
    Node *p;
    p=head->next;
    while(p->next!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("%d\n",p->data);
}
//链表拆分
Node *spilt(Node *head1)
{
    int cnt1=0,cnt2=0;//定义计数变量
    Node *p,*head2,*tail1,*tail2;

    head2=(Node *)malloc(sizeof(Node));//新开一个头节点
    head2->next=NULL;
    tail2=head2;

    p=head1->next;
    tail1=head1;//为拆分做准备
    head1->next=NULL;
    while(p)
    {
        if(p->data%2==0)//偶数时
        {
            tail1->next=p;//改变指向后,tail更新
            tail1=p;
            cnt1++;
        }
        else
        {
            tail2->next=p;
            tail2=p;
            cnt2++;
        }
        p=p->next;//继续处理下一个
    }
    tail1->next=NULL;//结尾保证置空,不乱指
    tail2->next=NULL;
    printf("%d %d\n",cnt1,cnt2);
    return head2;
}



int main()
{
    int n;
    Node *head1,*head2;
    cin>>n;
    head1=creat(n);
    head2=spilt(head1);
    ouput(head1);
    ouput(head2);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码敲上天.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值