当前位置: 首页 > news >正文

每日一练之合并两个有序链表

题目描述:

方法:双指针

代码实例:

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct ListNode
{
	int val;
	struct ListNode* next;
};
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, ListNode* list2)
{
	if (list1 == NULL)
	{
		return list2;
	}
	if (list2 == NULL)
	{
		return list1;
	}
	ListNode* newHead, * newTail;
	//创建空链表
	newHead = newTail = (ListNode*)malloc(sizeof(ListNode));
	ListNode* l1 = list1;
	ListNode* l2 = list2;
	while (l1 && l2)
	{
		if (l1->val < l2->val)//谁小往后插
		{
			newTail->next = l1;
			newTail = newTail->next;
			l1 = l1->next;
		}
		else
		{
			newTail->next = l2;
			newTail = newTail->next;
			l2 = l2->next;
		}
	}
	if (l1)
	{
		newTail->next = l1;
	}
	if (l2)
	{
		newTail->next = l2;
	}
	ListNode* ret = newHead->next;
	free(newHead);
	newHead = newTail = NULL;
	return ret;
}

接下来是我自己写的代码!

代码时间复杂度较高不建议模仿仅仅提供思路!

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if(list1==NULL)
    {
        return list2;
    }
    if(list2==NULL)
    {
        return list1;
    }
    ListNode* list1tail=list1;
    while(list1tail->next)
    {
        list1tail=list1tail->next;
    }
    list1tail->next=list2;
    ListNode* fast=list1;
    ListNode* slow=list1;
    int arr[100]={0};
    int i=0;
    while(fast)//把链表存储的val值放进数组
    {
        arr[i++]=fast->val;
        fast=fast->next;
    }
    for(int j=0;j<i;j++)//用冒泡排序进行升序
    {
        for(int k=0;k<i-1;k++)
        {
            if(arr[k]>arr[k+1])
            {
                int temp=arr[k];
                arr[k]=arr[k+1];
                arr[k+1]=temp;
            }
        }
    }
    int k=0;
    while(slow)//把数组的数据放回去
    {
        slow->val=arr[k++];
        slow=slow->next;
    }
    return list1;
}

完!!

 

相关文章:

  • 【0基础学Python】基础语法Part1
  • Next.js Server Action 提交 vs 前端 Fetch 提交:核心区别与优劣分析
  • 降级选型啊
  • 【向量模型】 开源通用向量模型BGE (BAAI General Embedding)
  • 英文字体:现代复古美学精致细节浓缩式衬线排版logo标题艺术字体 La Luxes Serif
  • 网络安全高级软件编程技术 网络安全 软件开发
  • 蓝桥杯备赛日记【day1】(c++赛道)
  • 解决VScode 连接不上问题
  • OpenWrt 源码目录分析与最终文件系统分析
  • CSS Web安全字体
  • Jump( 2015-2016 ACM-ICPC Northeastern European Regional Contest (NEERC 15). )
  • Autosar技术栈总目录
  • 系统安全阶段练习真题(高软44)
  • 基于DeepSeek与搜索引擎构建智能搜索摘要工具
  • c++:迭代器的失效
  • 星舰(Starship)近地轨道运力极限分析
  • 电路常用常用的定理/定律/计算方法
  • 【开源免费】基于SpringBoot+Vue.JS青年公寓服务平台(JAVA毕业设计)
  • 安装树莓派3B+环境(嵌入式开发)
  • FPGA学习篇——Verilog学习特别篇1(实现功能篇)
  • wordpress所有分类/四川seo快速排名
  • 建网站的目的是什么/品牌推广是做什么的
  • 做网站的软件dw/免费二级域名生成网站
  • 网站基础建设一般多少钱/二级域名查询网站
  • 网站建设合同按什么交印花税/希爱力双效片副作用
  • 来凡网站建设公司/关键词出价计算公式