206. 反转链表
206. 反转链表
给你单链表的头节点head
,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
解法一:
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reverseList(head *ListNode) *ListNode { cur := head var pre *ListNode for cur != nil { temp := cur.Next cur.Next = pre pre = cur cur = temp } return pre }
解法二:(递归)
func reverseList(head *ListNode) *ListNode { return help(nil, head) } func help(pre, head *ListNode)*ListNode{ if head == nil { return pre } next := head.Next head.Next = pre return help(head, next) }