反转链表的几种方法
1-最基础
func reverseList_1(head *ListNode) *ListNode {
if head == nil {
return nil
}
if head.Next == nil {
return head
}
p := head
q := p.Next
s := q.Next
for s != nil {
q.Next = p
p = q
q = s
s = s.Next
}
q.Next = p
head.Next = nil
head = q
return head
}
2-迭代
// 法2:迭代;
func reverseList_2(head *ListNode) *ListNode {
var prev *ListNode
cur := head
for cur != nil {
next := cur.Next
cur.Next = prev
prev = cur
cur = next
}
return prev
}
3-递归
// 法3:递归;
func reverseList(head *ListNode) *ListNode {
// 链表为空或只有单元素就不用再递归了;
if head == nil || head.Next == nil {
return head
}
p := reverseList(head.Next) // 递的过程;
// 归的过程;
head.Next.Next = head
head.Next = nil
return p
}