//deletionatposition.cpp#include <iostream>using namespace std;struct Node {int data;Node * prev;Node * next;Node(int d) { data = d; prev = next = NULL;}};Node * delPos(Node * head, int pos) {if (!head) return head;Node * curr = head;for (int i = 1; curr && i < pos; ++i) { curr = curr -> next;}if (!curr) return head;if (curr -> prev) curr -> prev -> next = curr -> next;if (curr -> next) curr -> next -> prev = curr -> prev;if (head == curr) head = curr -> next;delete curr;return head;}void display(Node * head) {Node * curr = head;while (curr != nullptr) { cout << curr -> data << " "; curr = curr -> next;}}int main() {struct Node * head = new Node(1);head -> next = new Node(2);head -> next -> prev = head;head -> next -> next = new Node(3);head -> next -> next -> prev = head -> next;cout << "Original Linked List: ";display(head);cout<<endl;cout << "After Deletion at the position 2: ";head = delPos(head, 2);display(head);return 0;}
# deletionatposition.pyclass Node: def __init__(self, data): self.data = data self.prev = None self.next = Nonedef delPos(head, pos): if not head: return head curr = head for i in range(1, pos): if curr is None: return head curr = curr.next if not curr: return head if curr.prev: curr.prev.next = curr.next if curr.next: curr.next.prev = curr.prev if head == curr: head = curr.next del curr return headdef display(head): curr = head while curr: print(curr.data, end=" ") curr = curr.next print()if __name__ == "__main__": head = Node(1) head.next = Node(2) head.next.prev = head head.next.next = Node(3) head.next.next.prev = head.next print("Original Linked List: ", end="") display(head) print("After Deletion at the position 2: ", end="") head = delPos(head, 2) display(head)
# deletionatend.pyclass Node: def __init__(self, data): self.data = data self.prev = None self.next = Nonedef delLast(head): if head is None: return None if head.next is None: del head return None curr = head while curr.next is not None: curr = curr.next curr.prev.next = None del curr return headdef display(head): curr = head while curr is not None: print(curr.data, end=" ") curr = curr.next print()if __name__ == "__main__": # Create the doubly linked list head = Node(1) head.next = Node(2) head.next.prev = head head.next.next = Node(3) head.next.next.prev = head.next print("Original Linked List: ", end="") display(head) print("After Deletion at the end: ", end="") head = delLast(head) display(head)