206. 反转链表
反转一个单链表。
迭代:
func reverseList(head *ListNode) *ListNode {
var pre *ListNode
cur := head
for cur != nil {
next := cur.Next
cur.Next = pre
pre = cur
cur = next
}
return pre
}
递归:
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newhead := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return newhead
}