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

输出样例如图:

代码如下:

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

相关推荐
likexuec3 小时前
数据结构(2)
数据结构
D e re k ZH5 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶6 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
十二1 天前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
D e re k ZH1 天前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
careathers1 天前
【数据结构】基于比较的排序算法 - 交换排序
数据结构·算法·排序算法
H.莓飛1 天前
【C++】【STL】vector_OJ题
linux·服务器·开发语言·数据结构·c++·visual studio
老师我太想进步了20262 天前
【数据结构-4】算法美学之顺序表
数据结构·算法
GrowingIO技术社区2 天前
CDP、行为分析、归因与营销自动化有什么区别?
数据结构·数据挖掘·数据分析
GrowingIO技术社区2 天前
实时标签怎样验收?从数据更新到分群可用
数据结构·数据挖掘·数据分析