条件:将两个有序的链表合并生成一个新的有序链表
第一部分:
- 创建链表及添加函数create
对于插入方法我选择的是头插法并且这次首次使用头指针下一个指向的才存有数据的方法.
struct Data
{
int number;
struct Data *next;
};
void Create(struct Data *pHead)
{
struct Data *p1, *t;
int d;
pHead->next = NULL;
p1 = pHead;
printf("请输入链表:");
scanf("%d", &d);
while(d != 0) {
t = (struct Data *)malloc(sizeof(struct Data));
t->number = d;
t->next = p1->next;
p1->next = t;
p1 = t;
scanf("%d", &d);
}
}
第二部分:打印函数print
- 具体代码如下
void print(struct Data *head) {
struct Data *p = head->next;
while(p != NULL) {
printf("%d ", p->number);
p = p->next;
}
printf("\n");
}
第三部分:合并函数merge
- 创建一个新的指针t作为新链表的头指针.
struct Data *merge(struct Data *pHeadA, struct Data *pHeadB) {
struct Data *pHead;
struct Data *p1, *p2, *t;
pHead = (struct Data *)malloc(sizeof(struct Data));
pHead->next = NULL;
p1 = pHeadA->next;
p2 = pHeadB->next;
t = pHead;
while(p1 && p2) {
if (p1->number <= p2->number) {
t->next = p1;
t = p1;
p1 = p1->next;
} else {
t->next = p2;
t = p2;
p2 = p2->next;
}
}
if (p1) {
t->next = p1;
} else {
t->next = p2;
}
return pHead;
}
后面的if意思是上面的循环结束后,总有一个链表循环完了,有可能是p1有可能是p2,if如果p1不为NULL,直接将p1全部接在t的后面即可,p2不为NULL同理.
第四部分:运行结果
- 主函数
int main() {
struct Data *pHead, *pHeadA, *pHeadB;
pHead = (struct Data *)malloc(sizeof(struct Data));
pHeadA = (struct Data *)malloc(sizeof(struct Data));
pHeadB = (struct Data *)malloc(sizeof(struct Data));
Create(pHeadA);
print(pHeadA);
Create(pHeadB);
print(pHeadB);
pHead = merge(pHeadA, pHeadB);
print(pHead);
}
- 运行结果为