Created
April 11, 2021 09:01
-
-
Save hsuRush/4f4f2b09a288a80215b6f4024775d635 to your computer and use it in GitHub Desktop.
a reverse LinkedList implementation in 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, data): | |
self.data = data | |
self.nextNode = None | |
def makeLinkedList(): | |
head = Node(10) | |
node = head | |
for i in range(9,0,-1): | |
nextNode = Node(i) | |
node.nextNode = nextNode | |
node = nextNode | |
return head | |
def printLinkedList(head): | |
print(head.data, end="") | |
node = head | |
while (node.nextNode != None): | |
node = node.nextNode | |
print(", "+ str(node.data), end="") | |
print() | |
def revLinkedList(head): | |
pastNode, curNode, nextNode = None, None, None | |
curNode = head | |
while(curNode.nextNode != None): | |
nextNode = curNode.nextNode | |
curNode.nextNode = pastNode | |
pastNode = curNode | |
curNode = nextNode | |
curNode.nextNode = pastNode | |
return curNode | |
head = makeLinkedList() | |
printLinkedList(head) | |
head = revLinkedList(head) | |
printLinkedList(head) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment