1. 程式人生 > 其它 >【資料結構】單鏈表的操作例2-3&4(TQ-P27)

【資料結構】單鏈表的操作例2-3&4(TQ-P27)

#include <bits/stdc++.h>

using namespace std;

//定義單鏈表結點型別
typedef struct LNode
{
    int data;           //每個節點存放一個數據元素
    struct LNode *next; //指標指向下一個節點
} LNode, *LinkList;

//LNode強調返回的是一個結點
//LinkList強調這是一個單鏈表

//初始化一個單鏈表(帶頭結點)
bool InitList(LinkList &L)
{
    L = (LNode *)malloc(sizeof(LNode)); //分配一個頭結點
    if (L == NULL)
    { //記憶體不足,分配失敗
        return false;
    }
    else
    {
        L->next = NULL; //頭結點之後暫時還沒有結點
        //養成好習慣,只要是初始化單鏈表,都先把頭指標指向NULL
    }
    return true;
}

//尾插法正向建立單鏈表
LinkList ListTailInsert(LinkList &L)
{
    InitList(L);      //初始化空表
    LNode *r = L, *s; //r為表尾指標
    int x;
    scanf("%d", &x);
    while (x != 9999)
    {
        s = (LNode *)malloc(sizeof(LNode));
        s->data = x;
        r->next = s;
        //在r結點之後插入元素x
        r = s;
        //r指向新的表尾結點
        //永遠保持r指向最後一個結點
        scanf("%d", &x);
    }
    r->next = NULL; //尾結點指標置空
    return L;
}

//列印函式(帶頭結點)
void print(LinkList &L)
{
    LNode *p = L->next;

    while (p != NULL)
    {
        if (p->next != NULL)
        {
            printf("%d->", p->data);
        }
        else
        {
            printf("%d", p->data);
        }
        p = p->next;
    }
    printf("\n");
}

//單鏈表歸併操作
void merge(LinkList &A, LinkList &B, LinkList &C)
{
    LNode *p = A->next; //p跟蹤A的最小值結點
    LNode *q = B->next; //q跟蹤B的最小值結點
    LNode *r = C;       //r始終指向C的終端結點
    while (p != NULL && q != NULL)
    { //當p與q都不空時,取p與q所指結點中較小的插入C的尾部
        if (p->data <= q->data)
        {
            r->next = p;
            p = p->next;
            r = r->next;
        }
        else
        {
            r->next = q;
            q = q->next;
            r = r->next;
        }
    }
    if (p != NULL)
    {
        r->next = p;
    }
    if (q != NULL)
    {
        r->next = q;
    }
}

int main()
{
    LinkList A, B, C;

    InitList(A);
    InitList(B);
    InitList(C);

    ListTailInsert(A);
    ListTailInsert(B);

    print(A);
    print(B);

    merge(A, B, C);

    print(C);

    return 0;
}

input:

1
3
5
9999
2
4
6
8
9999

output:

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