Skip to content

Instantly share code, notes, and snippets.

@mbartoli
Forked from nsfyn55/reverse.py
Created September 21, 2015 01:44
Show Gist options
  • Save mbartoli/c185da2b98ed5b2896a7 to your computer and use it in GitHub Desktop.
Save mbartoli/c185da2b98ed5b2896a7 to your computer and use it in GitHub Desktop.
Reverse Singly Linked List Python
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 recurse(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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment