Created
October 14, 2016 16:10
-
-
Save pranavgarg/0ded31eeb8ffc602c75343e942e7549b to your computer and use it in GitHub Desktop.
Python Reverse Link List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, value): | |
self._value = value | |
self._next = None | |
def __repr__(self): | |
return ("Node({!r})".format(self._value)) | |
def reverseList(head): | |
''' | |
reverses a linklist. | |
input: head of the link list | |
output: returns the head of the reversed link list | |
''' | |
prev = None | |
curr = head | |
while (curr is not None): | |
next = curr._next | |
curr._next, prev, curr = prev, curr, next | |
print ("AFTER: prev({!r}) curr({!r}) next ({!r})".format(prev,curr,next)) | |
return prev | |
def createLinkList(values_list): | |
''' | |
creates a linklist with an array of values. | |
input: array of values | |
output: returns the head of the created link list | |
''' | |
head = Node(0) | |
curr = head | |
for i in values_list: | |
temp = Node(i) | |
curr._next = temp | |
curr = curr._next | |
return head._next | |
def traverseList(head): | |
''' | |
traverses the elements of the link list | |
''' | |
l = head | |
while (l): | |
print "Node{!r} value: {}".format(l,l._value) | |
l = l._next | |
root = createLinkList(range(10,100,20)) | |
traverseList(root) | |
y = reverseList(root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment