c语言合并有序单链表(新增结点)//单链表结点结构体 typedef struct node{ datatype data; struct node* next;}L1和L2要在代码中输出
时间: 2024-05-13 12:15:05 浏览: 93
以下是一个合并两个有序单链表(L1 和 L2)并新增结点的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
//单链表结点结构体
typedef struct node {
int data;
struct node* next;
} Node;
//创建带头结点的单链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
//在单链表尾部插入结点
void appendNode(Node* head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
//合并有序单链表并新增结点
void mergeList(Node* L1, Node* L2, int data) {
Node* p1 = L1->next;
Node* p2 = L2->next;
Node* head = createList();
Node* tail = head;
while (p1 != NULL && p2 != NULL) {
if (p1->data < p2->data) {
tail->next = p1;
p1 = p1->next;
} else {
tail->next = p2;
p2 = p2->next;
}
tail = tail->next;
}
if (p1 == NULL) {
tail->next = p2;
} else {
tail->next = p1;
}
//在合并后的单链表尾部插入结点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newNode;
//输出合并后的单链表
printf("合并后的单链表:");
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
//释放内存
p = head;
while (p != NULL) {
Node* temp = p;
p = p->next;
free(temp);
}
}
int main() {
//创建 L1 单链表
Node* L1 = createList();
appendNode(L1, 1);
appendNode(L1, 3);
appendNode(L1, 5);
printf("L1 单链表:");
Node* p = L1->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
//创建 L2 单链表
Node* L2 = createList();
appendNode(L2, 2);
appendNode(L2, 4);
appendNode(L2, 6);
printf("L2 单链表:");
p = L2->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
//合并有序单链表并新增结点
mergeList(L1, L2, 7);
return 0;
}
```
输出结果:
```
L1 单链表:1 3 5
L2 单链表:2 4 6
合并后的单链表:1 2 3 4 5 6 7
```
阅读全文