資料結構實驗之鏈表四:有序鏈表的歸併,資料結構實驗歸併

來源:互聯網
上載者:User

資料結構實驗之鏈表四:有序鏈表的歸併,資料結構實驗歸併

  資料結構實驗之鏈表四:有序鏈表的歸併 Time Limit: 1000MS Memory limit: 65536K 題目描述分別輸入兩個有序的整數序列(分別包含M和N個資料),建立兩個有序的單鏈表,將這兩個有序單鏈表合并成為一個大的有序單鏈表,並依次輸出合并後的單鏈表資料。輸入第一行輸入M與N的值;
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。輸出輸出合并後的單鏈表所包含的M+N個有序的整數。樣本輸入
6 51 23 26 45 66 9914 21 28 50 100
樣本輸出
1 14 21 23 26 28 45 50 66 99 100
提示不得使用數組!來源 

樣本程式

#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;    tail=head;    for(i=1;i<=n;i++)    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);        p->next=NULL;        tail->next=p;        tail=p;    }    return head;}struct node * Merge(struct node *head1, struct node *head2){    struct node *p1, *p2, *tail;    p1=head1->next;    p2=head2->next;    tail=head1;    free(head2);    while(p1&&p2)    {    if(p1->data < p2->data)        {            tail->next=p1;            tail=p1;            p1=p1->next;        }        else        {            tail->next=p2;            tail=p2;            p2=p2->next;        }    }    if(p1)        tail->next=p1;    else        tail->next=p2;    return(head1);}int main(){    struct node * head1, *head2, *p;    int n, m;    scanf("%d %d",&n,&m);    head1=Creat(n);    head2=Creat(m);    p=Merge(head1,head2);    while(p->next->next!=NULL)    {        printf("%d ",p->next->data);        p=p->next;    }    printf("%d\n",p->next->data);    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.