206. 链表反转

文章目录
  1. 1. 解法

本文贴出单链表反转的代码

解法

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
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
var newHead: ListNode? = nil
var p = head
while p != nil {
let t = p?.next
p?.next = newHead
newHead = p
p = t
}
return newHead
}

func reverseList1(_ head: ListNode?) -> ListNode? {
return helper(nil, head)
}

func helper(_ pre:ListNode?, _ cur: ListNode?) -> ListNode? {
guard let p = cur else {
return nil
}

defer {
p.next = pre
}
guard let next = cur?.next else {
return p
}

let newHead = helper(cur, next)
return newHead
}
}