單連結串列的歸併(資料結構)

Emma1997發表於2016-09-22

思考:
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 <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

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;
}

相關文章