Skip to content

Instantly share code, notes, and snippets.

@liudonghua123
Last active June 21, 2018 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liudonghua123/110a82fbb4d4da580cff58106c599fdc to your computer and use it in GitHub Desktop.
Save liudonghua123/110a82fbb4d4da580cff58106c599fdc to your computer and use it in GitHub Desktop.
Simple python implementation of LinkedList
# 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