Skip to content

Commit

Permalink
Create Doubly linked list insertion at given position
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored May 14, 2024
1 parent 81488ef commit d187d17
Showing 1 changed file with 120 additions and 0 deletions.
120 changes: 120 additions & 0 deletions Doubly linked list insertion at given position
Original file line number Diff line number Diff line change
@@ -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;
}
}
}

0 comments on commit d187d17

Please sign in to comment.