用C语言编写一串代码,将两个升序的头指针型单链表合并为降序的头指针单链表
时间: 2023-05-26 11:06:01 浏览: 72
链表-使用C语言实现带头结点的单链表.zip
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *pNode;
pNode mergeList(pNode head1, pNode head2) {
pNode head3 = NULL, p = NULL;
while (head1 != NULL && head2 != NULL) {
if (head1->data >= head2->data) {
//头插法
pNode tmp = head1;
head1 = head1->next;
tmp->next = NULL;
if (head3 == NULL) {
head3 = tmp;
p = tmp;
} else {
tmp->next = head3;
head3 = tmp;
}
} else {
//同上
pNode tmp = head2;
head2 = head2->next;
tmp->next = NULL;
if (head3 == NULL) {
head3 = tmp;
p = tmp;
} else {
tmp->next = head3;
head3 = tmp;
}
}
}
//剩余的节点都连到 head3 的开头
while (head1 != NULL) {
pNode tmp = head1;
head1 = head1->next;
tmp->next = NULL;
if (head3 == NULL) {
head3 = tmp;
p = tmp;
} else {
tmp->next = head3;
head3 = tmp;
}
}
while (head2 != NULL) {
pNode tmp = head2;
head2 = head2->next;
tmp->next = NULL;
if (head3 == NULL) {
head3 = tmp;
p = tmp;
} else {
tmp->next = head3;
head3 = tmp;
}
}
return head3;
}
int main() {
pNode p1 = (pNode)malloc(sizeof(Node));
pNode p2 = (pNode)malloc(sizeof(Node));
pNode p3 = (pNode)malloc(sizeof(Node));
pNode p4 = (pNode)malloc(sizeof(Node));
pNode p5 = (pNode)malloc(sizeof(Node));
pNode p6 = (pNode)malloc(sizeof(Node));
p1->data = 1; p1->next = p2;
p2->data = 3; p2->next = p3;
p3->data = 5; p3->next = NULL;
p4->data = 2; p4->next = p5;
p5->data = 4; p5->next = p6;
p6->data = 6; p6->next = NULL;
pNode head1 = p1, head2 = p4;
printf("List1: ");
while (head1 != NULL) {
printf("%d ", head1->data);
head1 = head1->next;
}
printf("\nList2: ");
while (head2 != NULL) {
printf("%d ", head2->data);
head2 = head2->next;
}
pNode head3 = mergeList(p1, p4);
printf("\nMerged list: ");
while (head3 != NULL) {
printf("%d ", head3->data);
head3 = head3->next;
}
return 0;
}
```
阅读全文