数据结构:实验题目:单链表归并。将两个非递减次序排列的单链表归并为一个非递增次序排列的单链表,并计算表长。要求利用原来两个单链表的结点存放合并后的单链表。

输出样例如图:

代码如下:

cs 复制代码
#include<stdio.h>
 #include<stdlib.h>
 //链表节点结构
typedefstructListNode
 {
 intval;
 structListNode*next;
} ListNode;
 // 创建新节点
ListNode* createNode(int val)
 {
 ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
 newNode->val = val;
 newNode->next = NULL;
 return newNode;
 }
 // 插入节点到链表尾部
void insertTail(ListNode** head, int val)
 {
 ListNode* newNode = createNode(val);
 if (*head == NULL)
 {
 *head = newNode;
 }
 else
 {
 ListNode* temp = *head;
 while (temp->next != NULL)
 {
 temp = temp->next;
 }
 temp->next = newNode;
 }
 }
 // 释放链表内存
void freeList(ListNode* head)
 {
 ListNode* temp;
 while (head != NULL)
 {
 temp = head;
 head = head->next;
 free(temp);
 }
 }
 // 合并两个非递减链表为非递增链表
ListNode* mergeLists(ListNode* list1, ListNode* list2)
 {
 ListNode* result = NULL;
 while (list1 != NULL || list2 != NULL)

{
 ListNode* temp;
 if (list1 == NULL)
 {
 temp = list2;
 list2 = list2->next;
 }
 else if (list2 == NULL)
 {
 temp = list1;
 list1 = list1->next;
 }
 else if (list1->val < list2->val)
 {
 temp = list1;
 list1 = list1->next;
 }
 else
 {
 temp = list2;
 list2 = list2->next;
 }
 temp->next = result;
 result = temp;
 }
 return result;
 }
 // 计算链表长度
int listLength(ListNode* head)
 {
 int len = 0;
 while (head != NULL)
 {
 len++;
 head = head->next;
 }
 return len;
 }
 int main()
 {
 printf_s("230602207 侯冬明\n");
 ListNode* list1 = NULL;
 ListNode* list2 = NULL;
 int num;

// 输入第一个链表
printf_s("输入第一个非递减单链表,以-1 结束输入:\n");
 while (scanf_s("%d", &num) && num !=-1)
 {
 insertTail(&list1, num);
 }
 // 输入第二个链表
printf_s("输入第二个非递减单链表,以-1 结束输入:\n");
 while (scanf_s("%d", &num) && num !=-1)
 {
 insertTail(&list2, num);
 }
 ListNode* mergedList = mergeLists(list1, list2);
 int length = listLength(mergedList);
 printf_s("合并后的非递增单链表为:");
 ListNode* temp = mergedList;
 while (temp != NULL)
 {
 printf("%d ", temp->val);
 temp = temp->next;
 }
 printf_s("\n 合并后的单链表长度为:%d\n", length);
 freeList(list1);
 freeList(list2);
 freeList(mergedList);
 return 0;
 }

觉得有帮助就给博主点个关注叭~~

有问题的可以私信或者在评论区一起交流

友友们一起加油叭QAQ

相关推荐
别动哪条鱼5 小时前
AVAudioFifo
数据结构·ffmpeg·音视频
Croa-vo6 小时前
TikTok 数据工程师三轮 VO 超详细面经:技术深挖 + 建模推导 + 压力测试全记录
javascript·数据结构·经验分享·算法·面试
蘑菇小白6 小时前
时间复杂度
数据结构·算法
Cx330❀7 小时前
C++ STL set 完全指南:从基础用法到实战技巧
开发语言·数据结构·c++·算法·leetcode·面试
阿昭L8 小时前
堆结构与堆排序
数据结构·算法
.YM.Z17 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
sin_hielo21 小时前
leetcode 2435
数据结构·算法·leetcode
crescent_悦21 小时前
PTA L1-020 帅到没朋友 C++
数据结构·c++·算法
稚辉君.MCA_P8_Java1 天前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
cookqq1 天前
mongodb根据索引IXSCAN 查询记录流程
数据结构·数据库·sql·mongodb·nosql