Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Created January 1, 2019 14:24
Show Gist options
  • Save priyankvex/50a862aa475efb17d8be6531fcb509c6 to your computer and use it in GitHub Desktop.
Save priyankvex/50a862aa475efb17d8be6531fcb509c6 to your computer and use it in GitHub Desktop.
Scamming the coding interview : Problem 015 : Reverse the linked list
"""
Scamming the coding interview. Problem 015
Subscribe to our newsletter at https://scammingthecodinginterview.com/
to get a coding or design problem daily in your inbox and become exceptionally good at
coding interviews.
"""
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def reverse_linked_list(head):
temp_head = head
if not head:
return head
prev = head
curr = head.next
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
temp_head.next = None
return prev
def print_linked_list(head):
value = ""
while head:
value += (str(head.value) + "->")
head = head.next
print(value)
if __name__ == '__main__':
head = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
head.next = node_2
node_2.next = node_3
node_3.next = node_4
print_linked_list(head)
head = reverse_linked_list(head)
print_linked_list(head)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment