Last active
June 21, 2018 08:09
-
-
Save liudonghua123/110a82fbb4d4da580cff58106c599fdc to your computer and use it in GitHub Desktop.
Simple python implementation of LinkedList
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
# coding=utf-8 | |
class LinkedList(object): | |
# define the node type | |
class Node: | |
def __init__(self, element, next): | |
self.element = element | |
self.next = next | |
def __init__(self): | |
# create a header for linkedlist | |
self.header = LinkedList.Node(None, None) | |
def append(self, element): | |
node = LinkedList.Node(element, None) | |
# find the last node | |
currentNode = self.header | |
while currentNode and currentNode.next: | |
currentNode = currentNode.next | |
# append the node to the last | |
currentNode.next = node | |
def insertAt(self, element, position): | |
node = LinkedList.Node(element, None) | |
# find the node of the previous position | |
previousNode = self.header | |
currentNode = previousNode.next | |
while currentNode and position > 0: | |
previousNode = currentNode | |
currentNode = currentNode.next | |
position = position - 1 | |
node.next = previousNode.next | |
previousNode.next = node | |
def remove(self, element): | |
# find the node of the element | |
previousNode = self.header | |
currentNode = previousNode.next | |
while currentNode and currentNode.element != element: | |
previousNode = currentNode | |
currentNode = currentNode.next | |
# if the node found, else do nothing | |
if currentNode: | |
previousNode.next = currentNode.next | |
def removeAt(self, position): | |
# find the node of the previous position | |
previousNode = self.header | |
currentNode = previousNode.next | |
while currentNode and position > 0: | |
previousNode = currentNode | |
currentNode = currentNode.next | |
position = position - 1 | |
previousNode.next = currentNode.next | |
def isEmpty(self): | |
return self.header.next is not None | |
def printElements(self): | |
node = self.header.next | |
while node: | |
print(node.element) | |
node = node.next | |
if __name__ == "__main__": | |
linkedlist = LinkedList() | |
print("linkedlist.append 1, 2, 3") | |
linkedlist.append(1) | |
linkedlist.append(2) | |
linkedlist.append(3) | |
print("linkedlist.remove 2") | |
linkedlist.remove(2) | |
print("linkedlist.insertAt 4 at position 1") | |
print("linkedlist.insertAt 5 at position 0") | |
linkedlist.insertAt(4, 1) | |
linkedlist.insertAt(5, 0) | |
print("linkedlist.removeAt at position 2") | |
linkedlist.removeAt(2) | |
print("linkedlist.printElements") | |
linkedlist.printElements() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment