leetCode-0021_合并两个有序链表

题目描述

英文题目

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

1
2
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
中文题目

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

1
2
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解决方法

方法一
  • 描述

新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,由于两个输入链表的长度可能不同,所以最终会有一个链表先完成插入所有元素,则直接另一个未完成的链表直接链入新链表的末尾

  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
合并两个有序链表测试

@param l1 有序链表1
@param l2 有序链表2
@return 合并的有序链表
*/
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
if (l1 == NULL) {
return l2;
}

if (l2 == NULL) {
return l1;
}

struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next = NULL;

struct ListNode *p = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
p->next = l1;
l1 = l1->next;
}
else {
p->next = l2;
l2 = l2->next;
}
p = p->next;
}

if (l1) {
p->next = l1;
}
else {
p->next = l2;
}

return dummy->next;
}


/**
合并两个有序链表测试
*/
void mergeTwoLists_test()
{
SingleLinkListNode *head1 = single_link_list_create();
single_link_list_insert_tail(head1, 1);
single_link_list_insert_tail(head1, 2);
single_link_list_insert_tail(head1, 4);

SingleLinkListNode *head2 = single_link_list_create();
single_link_list_insert_tail(head2, 1);
single_link_list_insert_tail(head2, 3);
single_link_list_insert_tail(head2, 4);

printf("========合并两个有序链表测试========\n");
single_link_list_dump_head(head1);
single_link_list_dump_head(head2);
SingleLinkListNode *new = mergeTwoLists(head1->next, head2->next);
single_link_list_dump(new);
}

题目来源

Merge Two Sorted Lists

合并两个有序链表

线性表相关代码

数据结构-线性表