Contents

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

示例:

输入: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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newList = new ListNode(0);
ListNode current = newList;
while(l1 != null && l2 != null){
int one = l1.val;
int two = l2.val;
if(one <= two ){
current.next = l1;
l1 = l1.next;
current = current.next;

}else{
current.next = l2;
l2 = l2.next;
current = current.next;
}
}
if(l1 != null){
current.next = l1;
}

if(l2 != null){
current.next = l2;
}
return newList.next;
}

}
Contents