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
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList :
def __init__(self) :
self.head = None
self.tail = None
# Insert new node at end position
def insert(self, value) :
# Create a node
node = LinkNode(value)
if (self.head == None) :
# Add first node
self.head = 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) :
if (self.head == None) :
print("Empty Linked List")
else :
print("Linked List Head to Tail :", end = "")
# Get first node of linked list
temp = self.head
# iterate linked list
while (temp != None) :
# Display node value
print(" ", temp.data, end = " ")
# Visit to next node
temp = temp.next
print("\nLinked List Tail to Head :", end = "")
# Get last node of linked list
temp = self.tail
# iterate linked list
while (temp != None) :
# Display node value
print(" ", temp.data, end = " ")
# Visit to prev node
temp = temp.prev
def searchKey(self, key) :
# Get first node
front = self.head
# 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
# Empty Linked List
return False
def main() :
dll = DoublyLinkedList()
# 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
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.
New Comment