數據結構實驗之鏈表四:有序鏈表的歸併 (sdut oj)


數據結構實驗之鏈表四:有序鏈表的歸併

Time Limit: 1000MS Memory Limit: 65536KB


Problem Description

分別輸入兩個有序的整數序列(分別包含M和N個數據),建立兩個有序的單鏈表,將這兩個有序單鏈表合併成爲一個大的有序單鏈表,並依次輸出合併後的單鏈表數據。


Input

第一行輸入M與N的值; 
第二行依次輸入M個有序的整數;
第三行依次輸入N個有序的整數。


Output

輸出合併後的單鏈表所包含的M+N個有序的整數。


Example Input

6 5
1 23 26 45 66 99
14 21 28 50 100


Example Output

1 14 21 23 26 28 45 50 66 99 100

Hint

不得使用數組!

Author







參考代碼


#include<stdio.h>
#include<stdlib.h>

struct node
{
   int data;
   struct node *next;
};

int main()
{
    int n,m;
    struct node *head1,*head2,*tail,*p,*q;
    head1 = (struct node *)malloc(sizeof(struct node));
    head2 = (struct node *)malloc(sizeof(struct node));
    head1->next = head2->next =NULL;
    scanf("%d%d",&n,&m);
    tail = head1;
    while(n--)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next = tail->next;
        tail->next = p;
        tail = p;
    }
    tail = head2;
    while(m--)
    {
         p = (struct node *)malloc(sizeof(struct node));
         scanf("%d",&p->data);
         p->next = tail->next;
         tail->next = p;
         tail = p;
    }
    p = head1->next;
    q = head2->next;
    tail = head1;
    head1->next = head2->next = NULL;
    while( p && q )
    {
          if( p->data > q->data )
          {
               tail->next = q;
               tail = q;
               q = q->next;
          }
          else
          {
               tail->next = p;
               tail = p;
               p = p->next;
          }
    }
    if(p)
    {
        tail->next = p;
    }
    else
    {
        tail->next = q;
    }
    p = head1->next;
    printf("%d",p->data);
    p = p->next;
    while(p)
    {
       printf(" %d",p->data);
       p = p->next;
    }
    printf("\n");
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章