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

题目描述:

方法:双指针

代码实例:

cpp 复制代码
#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;
}

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

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

cpp 复制代码
/**
 * 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;
}

完!!

相关推荐
偷偷的卷1 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode
凤年徐1 小时前
【数据结构】时间复杂度和空间复杂度
c语言·数据结构·c++·笔记·算法
kualcal1 小时前
代码随想录17|二叉树的层序遍历|翻转二叉树|对称二叉树
数据结构·算法
钮钴禄·爱因斯晨2 小时前
C语言 | 函数核心机制深度解构:从底层架构到工程化实践
c语言·开发语言·数据结构
努力写代码的熊大3 小时前
链式二叉树数据结构(递归)
数据结构
yi.Ist3 小时前
数据结构 —— 键值对 map
数据结构·算法
爱学习的小邓同学3 小时前
数据结构 --- 队列
c语言·数据结构
s153353 小时前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
闻缺陷则喜何志丹3 小时前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
lifallen9 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree