206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
# @lc code=start
using LeetCode
reverse_list(head::Nothing) = head
function reverse_list(head::ListNode)::ListNode
new_head = pre_node = nothing
while !isnothing(head)
new_head = ListNode(head.val)
pre_node, new_head.next = new_head, pre_node
head = head.next
end
return new_head
end
# @lc code=end
reverse_list (generic function with 2 methods)
This page was generated using DemoCards.jl and Literate.jl.