剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
反转链表的几种方法
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
}