链表归并merge

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41668995/article/details/85217246

Merge two ordered lists into a new list in which the numbers are also in this order. If lengths of original two lists are m and n, the length of new linked list is m + n.

Input:

5
4 26 46 56 95
11
15 17 26 30 46 48 56 58 82 90 95

Output:

4 15 17 26 30 46 48 56 58 82 90 95

#include<stdio.h> 
#include<malloc.h> 
typedef struct Node
{
    int data;
    struct Node *next;
}Node, *LinkList;

void CreatList(LinkList &p, int n)
{
    p = (LinkList) malloc (sizeof(Node));
    p->next = NULL;
    LinkList p1 = p;
    LinkList p2;
    for (int i = 0; i < n; i++) {
        int a;
        scanf ("%d", &a);
        p2 = (LinkList) malloc (sizeof(Node));
        p1->next = p2;//将p1->next设为p2,不是把p1->next的值赋给p2
        p2->data = a;
        p1 = p2;
    }
    p1->next = NULL;
}

void Merge(LinkList &a, LinkList &b, LinkList &c)
{
    LinkList p1 = a->next;
    LinkList p2 = b->next;
    a->next = NULL;
    c = a;
    LinkList p3;//起到一个临时节点的作用,暂存p1->next 
    while (p1 && p2) {
        if (p1->data < p2->data) {//p1比p2小 
            p3 = p1->next;
            p1->next = NULL;
            a->next = p1;
            a = a->next;
            p1 = p3;
        }else if(p1->data == p2->data){//若两个链表中数据相等,只取一个 
        	p3 = p1->next;
            p1->next = NULL;
            a->next = p1;
            a = a->next;
            p1 = p3;
            p2 = p2->next;
		} else {
            p3 = p2->next;
            p2->next = NULL;
            a->next = p2;
            a = a->next;
            p2 = p3;
        }
    }
    if (p2) p1 = p2;//如果p2比p1长,把p2给p1 
    while (p1) {//即,将链表剩下的节点继续放入归并链表中 
        p3 = p1->next;
        p1->next = NULL;
        a->next = p1;
        a = a->next;
        p1 = p3;
    }
    free (b);
}

void PrintList(LinkList a)
{
    LinkList p = a->next;
    while (p) {
        printf ("%d ", p->data);
        p = p->next;
    }
    printf ("\n");
}

int main()
{
    int n, m;
    LinkList a, b, c;
    scanf ("%d", &m);
    CreatList(a, m);
    scanf ("%d", &n);
    CreatList(b, n);
    Merge(a, b, c);
    PrintList(c);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41668995/article/details/85217246