Skip to content

Instantly share code, notes, and snippets.

@bmwant
Created November 11, 2015 10:36
Show Gist options
  • Save bmwant/2aa6964ca69229e45f8e to your computer and use it in GitHub Desktop.
Save bmwant/2aa6964ca69229e45f8e to your computer and use it in GitHub Desktop.
Reverse linked list both iteratively and recursively
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def add(self, node):
if self.tail is not None:
self.tail.next = node
self.tail = node
else:
self.head = node
self.tail = node
def show(self):
current = self.head
while current is not None:
print(current.data, end=',')
current = current.next
print()
class Node(object):
def __init__(self, data):
self.next = None
self.data = data
def __str__(self):
return str(self.data)
def reverse_list(linked_list):
"""
Reverse linked list in place
"""
current = linked_list.head
last = None
while current is not None:
nxt = current.next
current.next = last
last = current
current = nxt
# Swipe head and tail
linked_list.head, linked_list.tail = linked_list.tail, linked_list.head
def reverse_list_recursively(linked_list):
def recurse(current, last):
if current is None:
return last
nxt = current.next
current.next = last
return recurse(nxt, current)
recurse(linked_list.head, None)
# Swipe head and tail
linked_list.head, linked_list.tail = linked_list.tail, linked_list.head
def run():
a = Node(1)
b = Node(3)
c = Node(5)
d = Node(9)
linked_list = LinkedList()
linked_list.add(a)
linked_list.add(b)
linked_list.add(c)
linked_list.add(d)
linked_list.show()
print(linked_list.head, linked_list.tail)
reverse_list_recursively(linked_list)
linked_list.show()
print(linked_list.head, linked_list.tail)
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment