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: 1->2->3->4->5

链表2: 3->4->5->6->7

输出: 1->2->3->3->4->4->5->5->6->7

源码

代码

1
2
3
4
5
6
7
class ListNode {
var node: Int
var nextNode: ListNode?
init(node: Int) {
self.node = node
}
}
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
class Solution {
//输出链表
func showList(head: ListNode) {
var printStr: String = ""
var first = head.nextNode
while (first != nil) {
if first!.nextNode != nil {
printStr = printStr.appending("\(first!.node)->")
}else
{
printStr = printStr.appending("\(first!.node)")
}
first = first!.nextNode
}
let firstStr = String(head.node)
guard printStr != "" else {
print(firstStr)
return
}
printStr = firstStr.appending("->\(printStr)")
print(printStr)
}
//整合链表
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
//1.
if l1!.node > l2!.node {
//2.
let temp = l2
//3.
temp!.nextNode = mergeTwoLists(l1, temp!.nextNode)
return temp
}else
{
//2.
let temp = l1
//3.
temp!.nextNode = mergeTwoLists(temp!.nextNode , l2)
return temp
}
}
}
  • 1.通过判断节点上的值
  • 2.获取到新链表的头部
  • 3.循环得到节点的下一个节点