单链表的归并(数据结构)

思考:
1、别忘了给头节点的next先赋值为NULL
2、将p1->next设为p2,不是把p1->next的值赋给p2

归并算法

void Merge(LinkList &a, LinkList &b)
{
    LinkList p1 = a->next;
    LinkList p2 = b->next;
    a->next = NULL;
    LinkList p3;
    while (p1 && p2) {//判断循环出去的条件
        if (p1->data <= p2->data) {
            p3 = p1->next;
            p1->next = a->next;
            a->next = p1;
            p1 = p3;
        } else {
            p3 = p2->next;
            p2->next = a->next;
            a->next = p2;//直接头插法插回a链表
            p2 = p3;
        }
    }
    if (p2) p1 = p2;
    while (p1) {//如果两个的长度不一样,则还要把长的那个也插到a链表
        p3 = p1->next;
        p1->next = a->next;
        a->next = p1;
        p1 = p3;
    }
    free (b);
}
#include 
#include 
#include 
#include 

using namespace std;

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

void CreatList(LinkList &p, int n)
{
     p = (LinkList) malloc (sizeof(Node));
     p->next = NULL;//别忘了给头节点的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 p1 = a->next;
    LinkList p2 = b->next;
    a->next = NULL;
    LinkList p3;
    while (p1 && p2) {
        if (p1->data <= p2->data) {
            p3 = p1->next;
            p1->next = a->next;
            a->next = p1;
            p1 = p3;
        } else {
            p3 = p2->next;
            p2->next = a->next;
            a->next = p2;
            p2 = p3;
        }
    }
    if (p2) p1 = p2;
    while (p1) {
        p3 = p1->next;
        p1->next = a->next;
        a->next = p1;
        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;
    scanf ("%d%d", &n, &m);
    LinkList a, b;
    CreatList (a, n);
    CreatList (b, m);
    Merge (a, b);
    PrintList (a);
    return 0;
}

你可能感兴趣的:(acm水题)