From d187d17e1bb3ae07729c3672b5b08f6da5b71fe8 Mon Sep 17 00:00:00 2001 From: Disha Thakurata <146114938+dishathakurata@users.noreply.github.com> Date: Tue, 14 May 2024 19:08:14 +0530 Subject: [PATCH] Create Doubly linked list insertion at given position --- ...ly linked list insertion at given position | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Doubly linked list insertion at given position diff --git a/Doubly linked list insertion at given position b/Doubly linked list insertion at given position new file mode 100644 index 0000000..3235244 --- /dev/null +++ b/Doubly linked list insertion at given position @@ -0,0 +1,120 @@ +//Doubly linked list insertion at given position + +import java.util.*; + +class Node { + int data; + Node next; + Node prev; + Node(int data) { + this.data = data; + next = prev = null; + } +} + +class DLinkedList { + Node newNode(Node head, int data) { + Node n = new Node(data); + if(head == null) { + head = n; + return head; + } + + head.next = n; + n.prev = head; + head = n; + return head; + } + + + void printList(Node node) { + Node temp = node; + while(temp.next != null) { + temp = temp.next; + } + + while(temp.prev != null) { + temp = temp.prev; + } + + while(temp != null) { + System.out.print(temp.data+" "); + temp = temp.next; + } + System.out.println(); + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + DLinkedList DLL = new DLinkedList(); + int t = sc.nextInt(); + + while(t > 0) { + Node temp; + Node head = null; + Node root = null; + int n = sc.nextInt(); + + for(int i = 0; i < n; i++) { + int x = sc.nextInt(); + head = DLL.newNode(head,x); + if(root == null) root = head; + } + + head = root; + int pos = sc.nextInt(); + int data = sc.nextInt(); + GfG g = new GfG(); + g.addNode(head,pos,data); + DLL.printList(head); + + while(head.next != null) { + temp = head; + head = head.next; + } + t--; + } + } +} + +class Node { + int data; + Node next; + Node prev; + + Node(int data) { + this.data = data; + next = prev = null; + } +} + +class GfG { + void addNode(Node head_ref, int pos, int data) { + Node newNode = new Node(data); + Node curr = head_ref; + int count = 0; + + while(curr != null) { + if(count == pos) { + break; + } + + count++; + curr = curr.next; + } + + if(curr.next == null) { + curr.next = newNode; + newNode.prev = curr; + newNode.next = null; + } + + else { + Node front = curr.next; + front.prev = newNode; + newNode.next = front; + newNode.prev = curr; + curr.next = newNode; + } + } +}