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

输出样例如图:

代码如下:

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

相关推荐
m0_547486665 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr5 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_35 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.5 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.5 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣5 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9925 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水5 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1015 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080546 天前
C++常见八股
数据结构·c++·算法