206_Reverse Linked List
Question
Solution 1: brute force (traverse twice)
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return head
# brute force
# convert to array
res = []
pointer = head
while pointer is not None:
res.append(pointer.val)
pointer = pointer.next
# convert back to a new linked list
ret = ListNode(res[0])
for item in res[1:]:
ret = self.helper(ret, item)
return ret
def helper(self, head, num):
ret = ListNode(num)
ret.next = head
return retIdea: reverse linked list when traverse each element (traverse once)
Solution 2: recursively
Solution 3: iteratively
Follow up: what if the final node is linked to itself?
Solution: iteratively
Last updated