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

来源:互联网 发布:论文中的财务报表数据 编辑:程序博客网 时间:2024/05/17 04:02
  1. 题目描述

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

    输入

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

    输出

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

    示例输入

    101 3 22 8 15 999 9 44 6 1001

    示例输出

    4 622 8 44 6 1 3 15 999 9 1001

  2. #include<stdio.h>   
  3. #include<stdlib.h>   
  4. struct node   
  5. {   
  6.     int date;   
  7.     struct node *next;   
  8. };   
  9. struct node *p,*q,*head1=NULL,*head2,*tail1,*tail2;   
  10. int main()   
  11. {   
  12.     int m,n,s;   
  13.     n=0;s=0;   
  14.     scanf("%d",&m);   
  15.     head2=(struct node*)malloc(sizeof(struct node));   
  16.     head1=(struct node*)malloc(sizeof(struct node));   
  17.     q=head1;   
  18.     while(m--)   
  19.     {   
  20.         if((p=(struct node*)malloc(sizeof(struct node)*1))==NULL)   
  21.             return 0;   
  22.         scanf("%d",&p->date);   
  23.         p->next=NULL;   
  24.             q->next=p;   
  25.             q=q->next;   
  26.   
  27.     }   
  28.     head2->next=NULL;   
  29.     tail1=head1;   
  30.     tail2=head2;   
  31.     p=head1->next;   
  32.     q=p->next;   
  33.     head1->next=NULL;   
  34.     while(p!=NULL)   
  35.     {   
  36.         if(p->date%2==0)   
  37.             {   
  38.                 p->next=NULL;   
  39.                 tail1->next=p;   
  40.                 tail1=p;   
  41.                 n++;   
  42.             }   
  43.         else  
  44.            {   
  45.             p->next=NULL;   
  46.             tail2->next=p;   
  47.             tail2=p;   
  48.             s++;   
  49.            }   
  50.            p=q;   
  51.            if(q!=NULL)   
  52.            q=q->next;   
  53.   
  54.     }   
  55.     printf("%d %d\n",n,s);   
  56.      q=head1->next;   
  57.     while(q!=NULL)   
  58.     {   
  59.         printf("%d",q->date);   
  60.         if(q->next!=NULL)   
  61.             printf(" ");   
  62.         q=q->next;   
  63.     }   
  64.     printf("\n");   
  65.   
  66.      p=head2->next;   
  67.     while(p!=NULL)   
  68.     {   
  69.         printf("%d",p->date);   
  70.         if(p->next!=NULL)   
  71.             printf(" ");   
  72.         p=p->next;   
  73.     }   
  74.     return 0;   
  75. }    
  76.   
0 0
原创粉丝点击