Skip to content

Instantly share code, notes, and snippets.

@nsfyn55
Last active October 17, 2018 22:09
Show Gist options
  • Save nsfyn55/3841544 to your computer and use it in GitHub Desktop.
Save nsfyn55/3841544 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 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)
@keithxm23
Copy link

On line shouldn't it be "return recurse(nxt, n)". I think that was a typo.

@pan87232494
Copy link

should be :
def recurse(n,last):
if n is None:
return last
nxt = n.nxt
n.nxt = last
return recurse(nxt, n) ----------> typo

@jschaf
Copy link

jschaf commented Nov 15, 2015

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