Search an element in doubly linked list in python

Python program for Search an element in doubly linked list. Here problem description and other solutions.

#  Python 3 program for
#  Find node in doubly linked list

#  This is Linked List Node
def __init__(self, data) :
self.data = data
self.next = None
self.prev = None

def __init__(self) :
self.tail = None

#  Insert new node at end position
def insert(self, value) :
#  Create a node
self.tail = node
return

#  Add node at last position
self.tail.next = node
node.prev = self.tail
self.tail = node

#  Display node element of doubly linked list
def display(self) :
else :
#  Get first node of linked list
while (temp != None) :
#  Display node value
print(" ", temp.data, end = " ")
#  Visit to next node
temp = temp.next

#  Get last node of linked list
temp = self.tail
while (temp != None) :
#  Display node value
print(" ", temp.data, end = " ")
#  Visit to prev node
temp = temp.prev

def searchKey(self, key) :
#  Get first node
#  Get last node
rear = self.tail
while (front != None and rear != None) :
if (front.data == key or rear.data == key) :
#  When node key exists
return True

if (front == rear or front.next == rear) :
#  When get middle nodes
return False

#  Visit to right node
front = front.next
#  Visit to left node
rear = rear.prev

return False

def main() :
#  Insert following linked list nodes
dll.insert(8)
dll.insert(2)
dll.insert(23)
dll.insert(-4)
dll.insert(7)
dll.insert(3)
dll.insert(9)
#  Display all node
dll.display()
key = -4
#  Test A
if (dll.searchKey(key)) :
print("\nNode key ", key ," are exist")
else :
print("\nNode key ", key ," are not exist")

#  Test B
key = 11
if (dll.searchKey(key)) :
print("Node key ", key ," are exist")
else :
print("Node key ", key ," are not exist")

#  Test C
key = 3
if (dll.searchKey(key)) :
print("Node key ", key ," are exist")
else :
print("Node key ", key ," are not exist")

if __name__ == "__main__": main()

Output

Linked List Head to Tail :  8   2   23   -4   7   3   9
Linked List Tail to Head :  9   3   7   -4   23   2   8
Node key  -4  are exist
Node key  11  are not exist
Node key  3  are exist

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.