Delete all nodes from a doubly linked list that are divisible by K
Question
Delete all nodes from a doubly linked list that are divisible by K
Solution
Sure, here is a Python solution for deleting all nodes from a doubly linked list that are divisible by K:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
if not self.head:
self.head = Node(data)
else:
new_node = Node(data)
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
new_node.prev = cur
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
def delete_nodes_divisible_by_k(self, k):
cur = self.head
while cur:
if cur.data % k == 0:
if cur.prev:
cur.prev.next = cur.next
if cur.next:
cur.next.prev = cur.prev
if cur == self.head:
self.head = cur.next
cur = cur.next
# Test the code
dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.append(3)
dll.append(4)
dll.append(5)
dll.append(6)
dll.append(7)
dll.append(8)
dll.append(9)
dll.append(10)
print("Original List:")
dll.print_list()
dll.delete_nodes_divisible_by_k(3)
print("List after deleting nodes divisible by 3:")
dll.print_list()
In this code, we first create a doubly linked list with nodes containing data from 1 to 10. Then we print the original list. After that, we call the delete_nodes_divisible_by_k method to delete all nodes that are divisible by 3. Finally, we print the list again to see the result.
Similar Questions
Write a Java function that delete odd nodes from the doubly linked list.
Given a doubly Linked list and a position. The task is to delete a node from a given position (position starts from 1) in a doubly linked list and return the head of the doubly Linked list.
What happens when you try to delete a node in a doubly linked list with only one node?The list becomes empty.The list becomes corrupted.The deletion fails.An error is thrown.
What is the best-case time complexity to delete a node from a doubly linked list?O(1)O(n)O(log n)O(n^2)
Write an function to delete an element from a doubly link list
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.