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

输出样例如图:

代码如下:

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

相关推荐
寒小松20 分钟前
Problem E: List练习
java·数据结构·list
清幽竹客1 小时前
redis数据结构-02(INCR、DECR、APPEND)
数据结构·redis
Akiiiira1 小时前
【数据结构】线性表
数据结构
小狗祈祷诗2 小时前
day20-线性表(链表II)
c语言·数据结构·链表
普通的冒险者2 小时前
几个简单的数组小练习(适合初学)
java·数据结构
How_doyou_do3 小时前
数据结构-堆
数据结构
小陈的进阶之路4 小时前
计算机大类专业数据结构下半期实验练习题
数据结构·算法·深度优先
不会计算机的捞地4 小时前
【数据结构入门训练DAY-30】数的划分
数据结构·算法·深度优先
@我漫长的孤独流浪6 小时前
最短路与拓扑(2)
数据结构·c++·算法
٩( 'ω' )و2606 小时前
哈希表的实现01
数据结构·c++·哈希算法·散列表