206. Reverse Linked List
https://leetcode.com/problems/reverse-linked-list
Python
Recursion
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self._travel(head, None)
def _travel(self, node, prev):
if not node:
return prev
origin_next = node.next
node.next = prev
return self._travel(origin_next, node)
Loop
(This is be used in 143. Reorder List)
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev
Go
Recursion
func reverseList(head *ListNode) *ListNode {
return travel(head, nil)
}
func travel(node *ListNode, prev *ListNode) *ListNode {
if node == nil {
return prev
}
originNext := node.Next
node.Next = prev
return travel(originNext, node)
}