用c语言编写具有将两个有序的单链表合并成一个有序的单链表功能的程序
时间: 2023-06-01 22:06:15 浏览: 103
好的,我可以帮您解答这个问题。以下是一个用C语言编写的将两个有序的单链表合并成一个有序的单链表的程序:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = NULL;
struct ListNode* tail = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
if (l1) {
tail->next = l1;
} else {
tail->next = l2;
}
return dummy->next;
}
int main() {
// create two sorted linked lists
struct ListNode* l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->val = 1;
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 2;
l1->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->next->val = 4;
l1->next->next->next = NULL;
struct ListNode* l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->val = 1;
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 3;
l2->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->next->val = 4;
l2->next->next->next = NULL;
// merge two linked lists
struct ListNode* mergedList = mergeTwoLists(l1, l2);
// print the merged linked list
printf("Merged Linked List:\n");
while (mergedList) {
printf("%d ", mergedList->val);
mergedList = mergedList->next;
}
printf("\n");
return 0;
}
```
这个程序的思路是先创建一个虚拟节点dummy,然后用tail指向dummy作为合并后链表的尾节点,再使用l1和l2指向两个要合并的单链表的头节点。然后遍历两个单链表,如果l1的当前节点的值小于l2的当前节点的值,则把l1的当前节点加到合并后链表的尾部,并且让l1的指针指向下一个节点;否则把l2的当前节点加到合并后链表的尾部,并且让l2的指针指向下一个节点。不断重复以上过程,直到l1或l2为空。最后如果l1不为空,则让合并后链表的尾部指向l1;否则让合并后链表的尾部指向l2。最后返回dummy的next即为合并后链表的头节点。
阅读全文