資料結構實驗之連結串列四:有序連結串列的歸併

HowieLee59發表於2019-03-10

Problem Description

分別輸入兩個有序的整數序列(分別包含M和N個資料),建立兩個有序的單連結串列,將這兩個有序單連結串列合併成為一個大的有序單連結串列,並依次輸出合併後的單連結串列資料。

Input

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

Output

輸出合併後的單連結串列所包含的M+N個有序的整數。

Sample Input

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

Sample Output

1 14 21 23 26 28 45 50 66 99 100

Hint

不得使用陣列!

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

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

void create(node * &head,int m){
    node *p,*tail;
    head = new Node;
    head->next = NULL;
    tail = head;
    for(int i = 0 ; i < m ;i++){
        p = new Node;
        scanf("%d",&p->data);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
}

void merge(node * &head1,node * &head2,node * &head){
    node *p,*p1,*p2;
    p = head;
    p->next = NULL;
    p1 = head1->next;
    p2 = head2->next;
    while(p1&&p2){
        if(p1->data > p2->data){
            p->next = p2;
            p = p2;
            p2 = p2->next;
        }else{
            p->next = p1;
            p = p1;
            p1 = p1->next;
        }
    }
    if(p1){
        p->next = p1;
    }else{
        p->next = p2;
    }
}

void show(node * &head){
    node *cur;
    cur = head->next;
    while(cur){
        if(cur->next == NULL){
            printf("%d\n",cur->data);
        }else{
            printf("%d ",cur->data);
        }
        cur = cur->next;
    }
}

int main(){
    node *head1,*head2,*head;
    head1 = new Node;
    head2 = new Node;
    head = new Node;
    int m,n;
    scanf("%d %d",&m,&n);
    create(head1,m);
    create(head2,n);
    merge(head1,head2,head);
    show(head);
    return 0;
}

 

相關文章