056_反转链表
知识点:链表、递归、迭代
LeetCode第两百零六题:https://leetcode-cn.com/problems/reverse-linked-list/submissions/
递归的解法比较难理解,但是细节简单,迭代容易理解但细节要小心处理。不过下面代码中迭代的写法是经过多次的简化的结果,一开始写出来的时候也是又丑又长,不过胜在平民化,易理解。
语言:GoLang
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// 递归,时空:O(n), O(n)
func reverseList_(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
last := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return last
}
// 迭代,时空:O(n), O(1),双百
func reverseList(head *ListNode) *ListNode {
var pre, nxt *ListNode
cur := head
for cur != nil {
nxt = cur.Next
cur.Next = pre
pre = cur
cur = nxt
}
return pre
}