第二十一题:合并两个有序链表
- 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
- 输入:l1 = [1,2,4], l2 = [1,3,4]
- 输出:[1,1,2,3,4,4]
示例 2:
- 输入:l1 = [], l2 = []
- 输出:[]
示例 3:
- 输入:l1 = [], l2 = [0]
- 输出:[0]
提示:
- 两个链表的节点数目范围是 [0, 50]
- -100 <= Node.val <= 100
- l1 和 l2 均按 非递减顺序 排列
解题:
/**
* @file 21.cpp
* @author HarkerYX
* @brief 合并两个有序链表
* @version 0.1
* @date 2021-05-03
*
* @copyright Copyright (c) 2021
*
*/
/*
第二十一题:合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解题思路:
循环遍历两个链表进行比较元素,然后依次把节点拿出来组成新链表
*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
struct ListNode {
int val;
struct ListNode *next;
};
void printList(struct ListNode* list)
{
struct ListNode* p = NULL;
p = (struct ListNode*)list;
printf("[ ");
while(p!=NULL)
{
printf("%d, ",p->val);
p = p->next;
}
printf(" ]\n");
}
struct ListNode * createListNode(int *num,int len)
{
struct ListNode *p = NULL;
struct ListNode *q = NULL;
struct ListNode *t = NULL;
for (int i = 0; i< len; i++){
q = (struct ListNode *)malloc(sizeof(ListNode) * 1);
q->val = num[i];
q->next = NULL;
if (i == 0)
t = p = q;
else{
t->next = q;
t = q;
}
}
// printList(p);
return p;
}
/**
* @brief
*
* @param l1
* @param l2
* @return struct ListNode*
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *q = NULL;
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
//暂时让指向第一个list开始
// q = ret = l1;
struct ListNode *head = NULL;
//创建一个头指向方便
head = (struct ListNode *)malloc(sizeof(struct ListNode) * 1);
q = head;
while(l1 && l2){
if(l1->val < l2->val){
q->next = l1;
l1 = l1->next;
}else{
q->next = l2;
l2 = l2->next;
}
q = q ->next;
}
//走到这里有可能有一个没走完,next就指向剩余就行
if(l1)
q->next = l1;
else
q->next = l2;
return head->next;
}
int main(void)
{
// 排序问题就默认在给值时候就排好了,没必要再去排序什么的
int num1[] = {1,2,3,4};
int num2[] = {1,3,4,5,6};
struct ListNode *l1 = NULL;
struct ListNode *l2 = NULL;
struct ListNode *ret = NULL;
l1 = createListNode(num1,sizeof(num1)/sizeof(int));
l2 = createListNode(num2,sizeof(num2)/sizeof(int));
ret = mergeTwoLists(l1,l2);
printList(ret);
return 0;
}
[ 1, 1, 2, 3, 3, 4, 4, 5, 6, ]