Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output:
[5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output:
[2,1]
Example 3:
Input: head = []
Output:
[]
Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
解題
Runtime: 0 ms, faster than 100%
Memory Usage: 2.9 MB, less than 7.14%
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseList(head *ListNode) *ListNode {if head ==nil {returnnil } arr :=make([]int, 0) n := headfor n !=nil { arr =append(arr, n.Val) n = n.Next } res :=&ListNode{ } cur := resfor i :=len(arr) -1; i >=0; i-- { cur.Next =&ListNode{ Val:arr[i] } cur = cur.Next }return res.Next}
二刷
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseList(head *ListNode) *ListNode { stack :=make([]*ListNode, 0)if head ==nil { returnnil }for head !=nil { stack =append(stack, head) head = head.Next }for i:=len(stack)-1; i>0; i-- { stack[i].Next = stack[i-1] } stack[0].Next =nilreturn stack[len(stack)-1]}