单链表的归并 noj

Description

假设两个按元素值非递减有序排列的线性表 A 和 B,均以单链表作为存储结构,试编写程序,将 A 表和 B 表归并成一个按元素值非递增有序排列的线性表 C,并要求利用原表(即A表和B表的)结点空间存放表 C。

Input

第一行输入两个正整数 m, n(m,n<=100),用空格分开,分别表示线性表 A 和 B 中元素个数,其后两行分别输入单链表 A 和 B。

Output

输出单链表 C。

Sample

Sample Input

5 5
1 3 7 12 16
2 6 7 13 20

Sample Output

20 16 13 12 7 7 6 3 2 1

代码(有注释)


代码(去掉注释)

#include <iostream>

using namespace std;

typedef struct Node {
    int data;
    struct Node* next;
} Node, * LinkList;

LinkList InitList();
void InsertNode(LinkList L, int num);

int main() {
    LinkList L1 = InitList();
    LinkList L2 = InitList();
    Node* p1, * p2;
    Node* h1, * h2;
    int num, count1, count2;

    cin >> count1 >> count2;
    while (count1--) {
        cin >> num;
        InsertNode(L1, num);
    }
    while (count2--) {
        cin >> num;
        InsertNode(L2, num);
    }
    p1 = L1->next;
    p2 = L2->next;
    h1 = L1;
    h2 = L2;
    while (p1 != NULL && p2 != NULL) {
        if (p2->data >= p1->data) {
            h1->next = p2;
            h2->next = h2->next->next;
            h1->next->next = p1;
            h1 = h1->next;
            p2 = h2->next;
        }
        else {
            p1 = p1->next;
            h1 = h1->next;
        }
    }
    if (p2 != NULL) {
        h1->next = p2;
    }
    p1 = L1->next;
    while (p1 != NULL) {
        cout << p1->data << " ";
        p1 = p1->next;
    }
}

LinkList InitList() {
    LinkList L = (LinkList)malloc(sizeof(Node));

    if (L == NULL) {
        cout << "Error on malloc new LinkList" << endl;
        exit(0);
    }
    L->next = NULL;
    return L;
}

void InsertNode(LinkList L, int num) {
    Node* p, * s;

    p = L;
    s = (Node*)malloc(sizeof(Node));
    if (s == NULL) {
        cout << "Error on malloc new Node" << endl;
        exit(0);
    }
    s->data = num;
    if (p->next == NULL) {
        s->next = NULL;
        p->next = s;
    }
    else {
        s->next = p->next;
        p->next = s;
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值