7-24 兩個有序連結串列序列的合併 (20 分)

明日可7發表於2018-09-22

題目:

已知兩個非降序連結串列序列S1與S2,設計函式構造出S1與S2合併後的新的非降序連結串列S3。

輸入格式:

輸入分兩行,分別在每行給出由若干個正整數構成的非降序序列,用−1表示序列的結尾(−1不屬於這個序列)。數字用空格間隔。

輸出格式:

在一行中輸出合併後新的非降序連結串列,數字間用空格分開,結尾不能有多餘空格;若新連結串列為空,輸出NULL

輸入樣例:

1 3 5 -1
2 4 6 8 10 -1

輸出樣例:

1 2 3 4 5 6 8 10

程式碼:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define LIST_INIT_SIZE 100000
#define LISTINCREMENT 10
#define mod 256
#define lowbit(x) (x&(-x))
#define mem(a,b) memset(a,b,sizeof(a))
#define FRER() freopen("in.txt","r",stdin);
#define FREW() freopen("out.txt","w",stdout);
using namespace std;
const int maxn = 10000 + 7;
typedef struct LNode{
    int data;
    struct LNode* next;
    struct LNode* tail;
}LNode,*LinkList;
void CreateList(LinkList& L){
    L = (LinkList)malloc(sizeof(LNode));
    L->next = NULL;
    L->tail = NULL;
    int n;
    int cnt = 0;
    while(~scanf("%d",&n)&&n!=-1){
        LinkList p = (LinkList)malloc(sizeof(LNode));
        p->data = n;
        if(cnt==0){
            L->next = p;
            p->next = NULL;
            L->tail = p;
        }
        else{
            LinkList q = L->tail;
            q->next = p;
            p->next = NULL;
            L->tail = p;
        }
        cnt++;
    }
}
void print(LinkList L){
    LinkList p = L->next;
    if(p==NULL) printf("NULL\n");
    else{
        int i = 0;
        while(p!=NULL){
            if(i++) printf(" ");
            printf("%d",p->data);
            p = p->next;
        }
        printf("\n");
    }
}
void MergeList(LinkList&A,LinkList&B,LinkList&C){
    LinkList pa,pb,pc;
    pa = A->next;
    pb = B->next;
    C = (LinkList)malloc(sizeof(LNode));
    pc = C;
    while(pa&&pb){
        if(pa->data<=pb->data){
            pc->next = pa;
            pc = pa;
            pa=pa->next;
        }else{
            pc->next = pb;
            pc = pb;
            pb = pb->next;
        }
    }
    pc->next = pa?pa:pb;
}
int main(){
    LinkList A,B,C;
    CreateList(A);
    CreateList(B);
    MergeList(A,B,C);
    print(C);
}

 

相關文章