Created
May 28, 2012 17:21
-
-
Save ptigas/2820165 to your computer and use it in GitHub Desktop.
linked list 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.next = None | |
self.prev = None | |
class LinkedList : | |
def __init__( self ) : | |
self.head = None | |
def add( self, data ) : | |
node = Node( data ) | |
if self.head == None : | |
self.head = node | |
else : | |
node.next = self.head | |
node.next.prev = node | |
self.head = node | |
def search( self, k ) : | |
p = self.head | |
if p != None : | |
while p.next != None : | |
if ( p.data == k ) : | |
return p | |
p = p.next | |
if ( p.data == k ) : | |
return p | |
return None | |
def remove( self, p ) : | |
tmp = p.prev | |
p.prev.next = p.next | |
p.prev = tmp | |
def __str__( self ) : | |
s = "" | |
p = self.head | |
if p != None : | |
while p.next != None : | |
s += p.data | |
p = p.next | |
s += p.data | |
return s | |
# example code | |
l = LinkedList() | |
l.add( 'a' ) | |
l.add( 'b' ) | |
l.add( 'c' ) | |
print l | |
l.remove( l.search( 'b' ) ) | |
print l |
def add( self, data ) :
node = Node( data )
if self.head == None :
self.head = node
else :
node.next = self.head
node.next.prev = node
self.head = node
#everytime we add a node, we create a temp node and give it the value self.head. so we adding from the front not the back ??
hey, you should explicitly mention that it is a doubly linked list.
The print call will just print an object and not the linkedlist data
Line 34 is is buggy and corrupting the backward list. It should be
node.next.prev = tmp
Also, for sake of completion, you need to release the instance of the node being deleted.
So add line after line 34
del p
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think according to proper implementation of doubly liked list please find below method for remove. If code is wrong please point out what is wrong in the below code.