'How to delete a node from in between, from a Doubly Circular Linked List in Python?
I want to delete a node from in between from a Doubly Circular Linked list.
I have written code for print the list; inserting the element at the beginning (push), at the end (append) and in between (insertAfter); and deleting node from the head and tail. This much part of the code is running correctly.
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DCLList:
def __init__(self):
self.head = None
self.tail = None
def createDCLL(self, value):
node = Node(value)
self.head = node
self.tail = node
node.next = node
node.prev = node
def gethead(self):
return self.head.value
def gettail(self):
return self.tail.value
def printlist(self):
temp = self.head
while temp:
print(temp.value, end = " ")
temp = temp.next
if temp == self.tail.next:
break
def push(self, value):
node = Node(value)
node.next = self.head
node.prev = self.tail
self.head.prev = node
self.head = node
self.tail.next = node
return
def append(self, value):
node = Node(value)
node.prev = self.tail
node.next = self.head
self.tail.next = node
self.tail = node
self.head.prev = node
return
def insertAfter(self, value, prev_node):
node = Node(value)
temp = self.head
while temp:
if prev_node == temp.value:
node.next = temp.next
node.prev = temp
node.next.prev = node
temp.next = node
return
temp = temp.next
if temp == self.tail.next:
break
if temp == self.tail.next:
print ("\nPrevious Node not found.")
return
def delete(self, value):
if (value == self.head.value):
temp = self.head
self.head = temp.next
temp.next.prev = self.tail
self.tail.next = temp.next
temp = None
return
if (value == self.tail.value):
temp = self.tail
self.tail = temp.prev
temp.prev.next = self.head
self.head.prev = temp.prev
temp = None
return
The problem I am facing is in deleting from in between. I have written this code, but it isn't working.
temp = self.head
while temp:
if (temp.value == value):
temp.prev.next = temp.next
temp.next.prev = temp.prev
temp = None
return
temp = temp.next
if temp == self.tail.next:
print ("\nValue not found.")
return
Expected Output is
>>> The original list is : 3 2 5
>>> After removing 2 from the list, we get : 3 5
What I am getting is
>>> The original list is : 3 2 5
>>> After removing 2 from the list, we get : 3 2 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
