Skip to content

Instantly share code, notes, and snippets.

@jesuyedavid
Last active April 24, 2018 18:11
Show Gist options
  • Save jesuyedavid/e24f32bf0db48bbd993102389df9aecc to your computer and use it in GitHub Desktop.
Save jesuyedavid/e24f32bf0db48bbd993102389df9aecc to your computer and use it in GitHub Desktop.
Reverse a linked list using iteration.
class Node:
def __init__(self, data):
self.data=data
self.nex=None
def revList(head):
trail=head
cur=head.nex
temp=cur.nex
trail.nex=None
while(temp!=None):
cur.nex=trail
trail=cur
cur=temp
temp=temp.nex
cur.nex=trail
start=cur
return start
#create list here
lls=Node(1)
lls.nex=Node(2)
lls.nex.nex=Node(3)
lls.nex.nex.nex=Node(4)
lls.nex.nex.nex.nex=Node(5)
lls.nex.nex.nex.nex.nex=Node(6)
lls.nex.nex.nex.nex.nex.nex=Node(7)
#helper function to print a given list
def printList(head):
cur=head
while (cur!=None):
print(cur.data)
cur=cur.nex
printList(revList(lls))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment