教我用c语言把两个有序递增的单链表合并为一个有序递增的单链表
时间: 2024-03-24 11:12:24 浏览: 75
好的,这是一个技术问题,我可以帮您解答。以下是代码实现:
```
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode prehead;
struct ListNode* prev = &prehead;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
prev->next = l1;
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
prev->next = l1 == NULL ? l2 : l1;
return prehead.next;
}
int main() {
//构造两个有序链表
struct ListNode* list1 = (struct ListNode*)malloc(sizeof(struct ListNode));
list1->val = 1;
struct ListNode* node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
node1->val = 2;
list1->next = node1;
node1->next = NULL;
struct ListNode* list2 = (struct ListNode*)malloc(sizeof(struct ListNode));
list2->val = 1;
struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
node2->val = 3;
list2->next = node2;
node2->next = NULL;
//输出原有序链表
printf("List 1: ");
struct ListNode* temp = list1;
while (temp) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
printf("List 2: ");
temp = list2;
while (temp) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
//调用合并函数,输出合并后的有序链表
struct ListNode* mergedList = mergeTwoLists(list1, list2);
printf("Merged List: ");
temp = mergedList;
while (temp) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
//释放动态分配的空间
free(list1);
free(node1);
free(list2);
free(node2);
return 0;
}
```
用C语言实现合并两个有序递增的单链表的方法是:首先设置一个前置节点prehead,用于连接两个有序链表,同时待定的指向prev用于追加节点;然后循环比较两个链表的节点值大小,将小的节点追加到prev所指向的位置;当一个链表的节点全部追加到新链表后,剩下的节点可以直接追加到新链表的最后,最后返回prehead.next节点即为合并后的有序链表。
阅读全文