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

输出样例如图:

代码如下:

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

相关推荐
QuantumLeap丶25 分钟前
《数据结构:从0到1》-05-数组
数据结构·数学
violet-lz41 分钟前
数据结构八大排序:希尔排序-原理解析+C语言实现+优化+面试题
数据结构·算法·排序算法
草莓工作室2 小时前
数据结构9:队列
c语言·数据结构·队列
violet-lz2 小时前
数据结构八大排序:堆排序-从二叉树到堆排序实现
数据结构·算法
爱学习的小鱼gogo2 小时前
python 单词搜索(回溯-矩阵-字符串-中等)含源码(二十)
开发语言·数据结构·python·矩阵·字符串·回溯·递归栈
浮灯Foden3 小时前
算法-每日一题(DAY18)多数元素
开发语言·数据结构·c++·算法·leetcode·面试
violet-lz3 小时前
数据结构八大排序:归并排序-原理+C语言实现+优化+面试题
c语言·数据结构·排序算法
如竟没有火炬4 小时前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
熬了夜的程序员5 小时前
【LeetCode】82. 删除排序链表中的重复元素 II
数据结构·算法·leetcode·链表·职场和发展·矩阵·深度优先
胖咕噜的稞达鸭7 小时前
AVL树手撕,超详细图文详解
c语言·开发语言·数据结构·c++·算法·visual studio