cubegao

Swift.合并两个排序的链表

2015-07-09

题目描述:

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
66
67
68
69
70
71
72
73
import Foundation

class For17Solution {
func mergeListNode(_ head1: ListNode?,_ head2: ListNode?) -> ListNode? {

if head1 == nil {
return head2
}

if head2 == nil {
return head1
}

var newHead : ListNode? = nil
var pHead = head1
var qHead = head2

if pHead!.val < qHead!.val {
newHead = pHead
pHead = pHead?.next
}else {
newHead = qHead
qHead = qHead?.next
}

var tempHead = newHead
while pHead != nil && qHead != nil {

if pHead!.val < qHead!.val {
tempHead?.next = pHead
pHead = pHead?.next
}else {
tempHead?.next = qHead
qHead = qHead?.next
}
tempHead = tempHead?.next
}

if pHead != nil {
tempHead?.next = pHead
}

if qHead != nil {
tempHead?.next = qHead
}

return newHead

}

func mergeListNode2(_ head1: ListNode?,_ head2: ListNode?) -> ListNode? {

if head1 == nil {
return head2
}

if head2 == nil {
return head1
}

var newHead: ListNode? = nil

if head1!.val < head2!.val {
newHead = head1
newHead?.next = mergeListNode2(head1?.next, head2)
}else {
newHead = head2
newHead?.next = mergeListNode2(head1, head2?.next)
}

return newHead
}
}

算法思想:有点类似合并两个排序数组。递归的话,相对好理解一点。

github地址:https://github.com/cubegao/LeetCode

Tags: 算法

扫描二维码,分享此文章