天天看點

C語言已知單連結清單LA=(a1,a2,…,am)和LB=(b1,b2,…,bn),編寫程式按以下規則将它們合并成一個單連結清單LC,

 LC=(a1,b1,…,am,bm,bm+1,…,bn),m<=n

或者

LC=(a1,b1,…,bn,an,an+1,…,am),m>n

/*

開發者:慢蝸牛 開發時間:2020.6.11

程式功能:合并連結清單

*/

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct L)

void print(struct L* head);
void insert(struct L* p1, struct L* p2);

struct L//建立結構體
{
int a;

struct L* next;
};

int n;

struct L* creat()//建立連結清單
{
struct L* head;

struct L* p1, * p2;

n = 0;

p1 = p2 = (struct L*)malloc(LEN);

scanf_s("%d", &p1->a);

head = NULL;

while (p1->a != -1)
{
    n = n + 1;

    if (n == 1) head = p1;

    else p2->next = p1;

    p2 = p1;

    p1 = (struct L*)malloc(LEN);

    scanf_s("%d", &p1->a);
}

p2->next = NULL;

return(head);
}

void print(struct L* head)//輸出具有頭結點的清單
{
struct L* p;

p = head->next;

if (head != NULL)
    do
    {
        printf("--%d ", p->a);

        p = p->next;
    } while (p != NULL);
}

void insert(struct L* p1, struct L* p2)//從小到大合并遞增連結清單
{
struct L* LC, * r;

LC = (struct L*)malloc(LEN);

LC->next = p1;

r = LC;

while (p1 && p2)
{
    if (p1->a <= p2->a)
    {
        r->next = p1;

        r = p1;

        p1 = p1->next;
    }

    else
    {
        r->next = p2;

        r = p2;
    
        p2 = p2->next;
    }

}
if (p1 == NULL) r->next = p2;

else r->next = p1;

print(LC);
}

void main()//主函數
{
struct L* LA, * LB;

printf("請輸入LA的資料:");

LA = creat();

printf("請輸入LB的資料:");

LB = creat();

printf("LC=");

insert(LA, LB);
}
           

繼續閱讀