[算法学习]合并两个排序的链表

问题描述: 合并两个排序的链表。

解法一:用递归

解法: 递归比较结点大小:每次递归,取出两个链表的头结点来比较,比较小的结点加入新链表中。


参考代码如下

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
/**
* 用递归
* @param head1
* @param head2
* @return
*/

public static ListNode merge(ListNode head1, ListNode head2)
{

if(head1==null)
{
return head2;
}
if(head2==null)
{
return head1;
}
ListNode head;
if(head1.value<head2.value)
{
head=head1;
head.next=merge(head1.next, head2);
}
else
{
head=head2;
head.next=merge(head1, head2.next);
}
return head;
}

解法二:用循环

解法: 使用指针移动的方式来遍历两个链表。每次两个指针停止,进行结点比较,较小的结点加到新链表中。


参考代码如下

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
/**
* 用循环
* @param head1
* @param head2
* @return
*/

public static ListNode merge1(ListNode head1, ListNode head2)
{

if (head1 == null)
{
return head2;
}
if (head2 == null)
{
return head1;
}
ListNode head;
if (head1.value < head2.value)
{
head = head1;
head1 = head1.next;
}
else
{
head = head2;
head2 = head2.next;
}
ListNode move = head;
while (head1 != null || head2 != null)
{
if (head1 == null)
{
move.next = head2;
head2 = head2.next;
}
else if (head2 == null)
{
move.next = head1;
head1 = head1.next;
}
else if (head1.value < head2.value)
{
move.next = head1;
head1 = head1.next;
}
else
{
move.next = head2;
head2 = head2.next;
}
if(move.value>move.next.value)
{
System.err.println("输入的链表不是有序的");
return null;
}
move = move.next;
}
return head;
}