Last active
October 17, 2018 22:09
-
-
Save nsfyn55/3841544 to your computer and use it in GitHub Desktop.
Reverse Singly Linked List Python
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,val,nxt): | |
self.val = val | |
self.nxt = nxt | |
def prnt(n): | |
nxt = n.nxt | |
print n.val | |
if(nxt is not None): | |
prnt(nxt) | |
#Iterative | |
def reverse(n): | |
last = None | |
current = n | |
while(current is not None): | |
nxt = current.nxt | |
current.nxt = last | |
last = current | |
current = nxt | |
return last | |
#Recursive | |
def recurse(n,last): | |
if n is None: | |
return last | |
nxt = n.nxt | |
n.nxt = last | |
return reverse(nxt, n) | |
n0 = Node(4,None) | |
n1 = Node(3,n0) | |
n2 = Node(2,n1) | |
n3 = Node(1,n2) | |
#l = reverse(n3) | |
prnt(n3) | |
result = recurse(n3, None) | |
prnt(result) |
It took me a long while to figure out the recursive version. I added some variable names that others might find helpful..
def reverse(node):
def reverse_helper(old_head, new_head):
if old_head is None:
return new_head
next_old_head = old_head.nxt
old_head.nxt = new_head
return reverse_helper(next_old_head, old_head)
return reverse_helper(node, None)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
should be :
def recurse(n,last):
if n is None:
return last
nxt = n.nxt
n.nxt = last
return recurse(nxt, n) ----------> typo