資料結構實驗之鏈表五:單鏈表的拆分,資料結構單鏈

來源:互聯網
上載者:User

資料結構實驗之鏈表五:單鏈表的拆分,資料結構單鏈

  資料結構實驗之鏈表五:單鏈表的拆分 Time Limit: 1000MS Memory limit: 65536K 題目描述輸入N個整數順序建立一個單鏈表,將該單鏈表拆分成兩個子鏈表,第一個子鏈表存放了所有的偶數,第二個子鏈表存放了所有的奇數。兩個子鏈表中資料的相對次序與原鏈表一致。輸入第一行輸入整數N;;
第二行依次輸入N個整數。輸出第一行分別輸出偶數鏈表與奇數鏈表的元素個數;
第二行依次輸出偶數子鏈表的所有資料;
第三行依次輸出奇數子鏈表的所有資料。樣本輸入
101 3 22 8 15 999 9 44 6 1001
樣本輸出
4 622 8 44 6 1 3 15 999 9 1001
提示不得使用數組!來源
#include<stdio.h>#include<stdlib.h>struct node {    int data;    struct node *next;};struct node *Creat(int n){    struct node *head, *tail, *p;    int i;    head=(struct node *)malloc(sizeof(struct node));    head->next=NULL;    for(i=1;i<=n;i++)    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);        p->next=head->next;        head->next=p;    }    return head;}struct node * Split(struct node * head1){    struct node *head2, *p, *q;    int a=0, b=0;    head2=(struct node *)malloc(sizeof(struct node));    head2->next=NULL;    p=head1->next;    head1->next=NULL;    q=p->next;    while(p!=NULL)    {        if(p->data%2==0)        {            p->next=head1->next;            head1->next=p;            a++;        }        else        {            p->next=head2->next;            head2->next=p;            b++;        }        p=q;        if(q!=NULL)        q=q->next;    }    printf("%d %d\n",a,b);    return head2;};int main(){    int n;    struct node * head1, *head, *p, *q;    scanf("%d",&n);    head=Creat(n);    head1=Split(head);    p=head->next;    while(p!=NULL)    {        if(p->next!=NULL)            printf("%d ",p->data);        else            printf("%d\n",p->data);        p=p->next;    }    q=head1->next;    while(q!=NULL)    {        if(q->next!=NULL)            printf("%d ",q->data);        else            printf("%d\n",q->data);        q=q->next;    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.