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


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

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

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

    Input

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

    Output

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

    Example Input

    10
    1 3 22 8 15 999 9 44 6 1001

    Example Output

    4 6
    22 8 44 6 
    1 3 15 999 9 1001

    #include <iostream>
    #include <stdlib.h>
    #include <malloc.h>
    using namespace std;
    #define LISTSIZE 1000
    #define LISTMAX 100
    typedef int Elemtype;
    typedef struct LNode
    {
        Elemtype data;
        struct LNode *next;
    }LNode,*LinkList;
    void display(struct LNode *head)
    {
        LNode *p;
        p = head->next;
        while(p!=NULL)
        {
            if(p->next==NULL)
            {
                cout<<p->data<<endl;
            }
            else
            {
                cout<<p->data<<" ";
            }
            p=p->next;
        }
    }
    LNode *createLNode(int n)
    {
    int k1,k2;
    k1=k2=0;
        int i;
        LNode *head,*p,*tail,*head1,*tail1;
        head = (LNode *)malloc(sizeof(LNode));
    head1 = (LNode *)malloc(sizeof(LNode));
        head->next = NULL;
    head1->next = NULL;
        tail = head;
    tail1 = head1;
        for(i=0;i<n;i++)
        {
            p = (LNode *)malloc(sizeof(LNode));
            cin>>p->data;
    if(p->data%2==0)
    {
            tail->next = p;
            tail = p;
    tail->next=NULL;
    k1++;
    }
    else
    {
    tail1->next = p;
            tail1 = p;
    tail1->next=NULL;
    k2++;
    }
        }
    printf("%d %d\n",k1,k2);
    display(head);
    display(head1);
        return head;
    }
    /*
    void merge(struct LNode *head)
    {
    LNode *p,*h1,*h2,*t1,*t2,*p1,*p2;
    h1=h2 = (LNode *)malloc(sizeof(LNode));
    h1->next=h2->next=NULL;
    t1=h1;
    t2=h2;
        p = head->next;
        while(p!=NULL)
        {
            if(p->data%2!=0)
            {
                p1 = (LNode *)malloc(sizeof(LNode));
    p1->data=p->data;
                t1->next = p1;
    t1 = p1;
    t1->next=NULL;
            }
            else
            {
    p2 = (LNode *)malloc(sizeof(LNode));
    p2->data=p->data;
                t2->next = p2;
    t2 = p2;
    t2->next=NULL;
            }
    p=p->next;
        }
    display(h1);
    display(h2);
    }
    */
    int main()
    {
        LNode *L;
        int n;
        cin>>n;
        L = createLNode(n);
        //merge(L);
        return 0;
    }

  • 相关阅读:
    区块链|学习笔记(三)
    左神算法之获取栈中最小值
    23种设计模式之适配器模式
    二叉树序列化和反序列化
    归并排序
    通过集合构建RDD或者DataFrame
    内核源码分析——shuffle
    问题
    函数参数
    问题记录
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/6444607.html
Copyright © 2020-2023  润新知