206.反转链表
2021-04-18 本文已影响0人
faterman
1.正向遍历,移动指针
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
var pre: ListNode? = nil
var current = head
while current != nil {
let tmp_next = current?.next
current?.next = pre
pre = current
current = tmp_next
}
return current
}
}
2.递归
class Solution {
func reverseList(_ head: ListNode?) -> ListNode? {
if head == nil || head?.next == nil {
return head
}
let newHead = reverseList(head?.next)
head?.next?.next = head
head?.next = nil
return newHead
}
}