Linked Lists in Python

python Linked List

Learn how to implement a linked list in python without any help of packages

If you want to become a good programmer, you should know what is a linked list. And you should also know how to implement a linked list.

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

# sample code
l = LinkedList()

l.add( 'a' )
l.add( 'b' )
l.add( 'c' )

print l
l.remove( l.search( 'b' ) )
print
print l

Similar Posts:

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

You May Also Like

About the Author: shakirck

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.