1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | #!/usr/bin/env python class Node( object ): def __init__( self ): self . next = None self .previous = None self .element = None class LinkedList( object ): def __init__( self ): self .n = 0 self .last = Node() self .first = self .last def append( self , element): self .last.element = element self .last. next = Node() tmp = self .last self .last = self .last. next self .last.previous = tmp self .n + = 1 def front( self ): if self .n = = 0 : return None e = self .first.element self .first = self .first. next self .n - = 1 return e def back( self ): if self .n = = 0 : return None e = self .last.previous.element self .last = self .last.previous self .last. next = Node() self .n - = 1 return e def size( self ): return self .n def elements( self ): i = self .first while i.element: yield i.element i = i. next if __name__ = = "__main__" : l = LinkedList() assert None = = l.front() assert None = = l.back() l.append( 1 ) l.append( 2 ) l.append( 3 ) assert 1 = = l.front() assert 2 = = l.front() assert 3 = = l.front() l.append( 1 ) l.append( 2 ) l.append( 3 ) assert 3 = = l.back() assert 2 = = l.back() assert 1 = = l.back() l.append( 1 ) assert 1 = = l.back() l.append( 1 ) assert 1 = = l.front() |
Sunday, April 22, 2012
How to Implement Doubly Linked List in Python
This is my simple implementation of doubly linked list in Python.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment