两个有序链表序列的合并 c语言,两个有序链表序列的合并

该博客主要介绍了如何使用C语言实现链表的初始化、读取数据、合并两个已排序链表以及打印链表内容。通过`InitList`函数创建空链表,`read`函数读取整数数据并插入链表,`combine`函数根据元素大小合并两个链表,最后`print`函数遍历并打印链表。示例代码展示了基本的链表操作技巧。
摘要由CSDN通过智能技术生成

#include#includetypedef struct Node* List;

struct Node {

int data;

struct Node *Next;

};

List InitList();

void print(List l);

void read(List l);

void combine(List l1,List l2,List l3);

int main() {

List l1,l2,l3;

l1=InitList();

l2=InitList();

l3=InitList();

read(l1);

read(l2);

combine(l1,l2,l3);

print(l3);

return 0;

}

List InitList() {

List l;

l=(List)malloc(sizeof(struct Node));

if(!l) return NULL;

l->Next=NULL;

return l;

}

void print(List l) {

l=l->Next;

if(l==NULL) {

printf("NULL");

return;

}

while(l) {

if(l->Next==NULL)

printf("%d",l->data);

else printf("%d ",l->data);

l=l->Next;

}

}

void read(List l) {

List tmp;

int data;

scanf("%d",&data);

while(data>0) {

tmp=(List)malloc(sizeof(struct Node));

if(!tmp) return;

tmp->data=data;

tmp->Next=NULL;

l->Next=tmp;

l=tmp;

scanf("%d",&data);

}

return;

}

void combine(List l1,List l2,List l3) {

l1=l1->Next;

l2=l2->Next;

while(l1!=NULL&&l2!=NULL) {

if(l1->data>l2->data) {

l3->Next=l2;

l2=l2->Next;

} else {

l3->Next=l1;

l1=l1->Next;

}

l3=l3->Next;

}

if(l1==NULL&&l2==NULL) return;

if(l1!=NULL)

l3->Next=l1;

else l3->Next=l2;

return;

}

C语言中,合并两个有序链表可以采用迭代或者递归的方式实现。这里是一个简单的迭代方法的示例: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct ListNode { int val; struct ListNode* next; } ListNode; // 合并两个有序链表 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // 创建一个新的头节点,并初始化为NULL ListNode* dummy = (ListNode*)malloc(sizeof(ListNode)); dummy->next = NULL; ListNode* current = dummy; // 当前指针 while (l1 != NULL && l2 != NULL) { // 只要任一链表非空 if (l1->val <= l2->val) { // 将较小的值节点插入当前节点 current->next = l1; l1 = l1->next; } else { current->next = l2; l2 = l2->next; } current = current->next; // 移动到下一个位置 } // 如果其中一个链表已经遍历完,则将另一个链表剩余部分添加到结果链表尾部 if (l1 != NULL) { current->next = l1; } else { current->next = l2; } return dummy->next; // 返回新的头节点 } // 测试函数 void printList(ListNode* head) { ListNode* temp = head; while (temp != NULL) { printf("%d ", temp->val); temp = temp->next; } printf("\n"); } int main() { // 创建两个示例链表 ListNode* list1 = (ListNode*)malloc(sizeof(ListNode)); list1->val = 1; list1->next = (ListNode*)malloc(sizeof(ListNode)); list1->next->val = 2; list1->next->next = NULL; ListNode* list2 = (ListNode*)malloc(sizeof(ListNode)); list2->val = 3; list2->next = (ListNode*)malloc(sizeof(ListNode)); list2->next->val = 4; list2->next->next = NULL; // 合并链表 ListNode* merged = mergeTwoLists(list1, list2); // 打印合并后的链表 printList(merged); return 0; } ``` 在这个例子中,`mergeTwoLists` 函数接收两个有序链表的头节点作为参数,返回合并后的有序链表头节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值