Reverse a singly linked list.
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
Runtime : 32 ms
https://www.geeksforgeeks.org/reverse-a-linked-list/
참조
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def reverse(node: ListNode, prev: ListNode = None):
if not node:
return prev
next, node.next = node.next, prev
return reverse(next, node)
return reverse(head)
Runtime : 36 ms