Created
February 16, 2014 16:25
-
-
Save rctay/9036785 to your computer and use it in GitHub Desktop.
Python: linked lists
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(object): | |
prev = None | |
next = None | |
value = None | |
def __init__(self, prev, value): | |
self.value = value | |
self.appendTo(prev) | |
def unlink(self): | |
if self.prev: | |
self.prev.next = self.next | |
if self.next: | |
self.next.prev = self.prev | |
self.prev = None | |
self.next = None | |
def appendTo(self, node): | |
self.prev = node | |
if node is None: | |
return | |
if node.next: | |
node.next.prev = self | |
self.next, node.next = node.next, self | |
def __iter__(self): | |
v = self | |
while v is not None: | |
yield v | |
v = v.next | |
LinkedList = Node | |
head = LinkedList(None, None) | |
head.last = head | |
# appending | |
head.last = Node(head.last, 5) | |
# removing | |
if head.last == node: | |
head.last = node.prev | |
node.unlink() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment