【题目】
设计将两个有序链表合并成一个单链表并保持有序的算法
【代码】
#define _CRT_SECURE_NO_WARNINGS 1
#pragma warning(disable:6031)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int elem;
typedef struct LNode {
elem data;
struct LNode* next;
}LNode,*List;
//尾插法建立链表
void List_TailInsert(List& L) {
//带有头结点的链表
elem data;
LNode* head = (LNode*)malloc(sizeof(LNode)),*p;
head->next = NULL;
L = head; //声明一个头结点
scanf("%d", &data);
while (data != 999) {
p = (LNode*)malloc(sizeof(LNode));
p->data = data;
p->next = NULL;
head->next = p;
head = head->next;
scanf("%d", &data);
}
head->next = NULL;
}
//算法主体
void merge(List A, List B, List &C) {
LNode* cur_A=A->next,*cur_B=B->next, * p;
p = (LNode*)malloc(sizeof(LNode)); //头指针
p->next = NULL;
C = p;
while (cur_A&&cur_B){ //使用&&是为了降低时间复杂度
if (cur_A->data <= cur_B->data) {
p->next = cur_A;
cur_A = cur_A->next;
p = p->next;
}
else{
p->next = cur_B;
cur_B= cur_B->next;
p = p->next;
}
}
p->next = NULL;
if (cur_A)
p->next = cur_A;
if (cur_B)
p->next = cur_B;
}
void prin(LNode* p) {
while (p) {
printf("%d\t", p->data);
p = p->next;
}
}
int main() {
List L1, L2, L3;
printf("=====Insert start======\n");
List_TailInsert(L1);
printf("\n=====Insert end======\n");
printf("=====Insert start======\n");
List_TailInsert(L2);
printf("\n=====Insert end======\n");
prin(L1->next);
printf("\n");
prin(L2->next);
printf("\n");
merge(L1,L2,L3);
prin(L3->next);
printf("\n");
return 0;
}
【运行结果】
【补充说明】
typedef struct LNode {
elem data;
struct LNode* next;
}LNode,*List; //List是指针类型
List L1, L2, L3; //所以此处L1,L2,L3 均是指针类型的链表
void merge(List A, List B, List &C) //该函数的传入参数也是指针类型,
//所以此函数运行完毕后,L1,L2的内的值一般会发生改变