Skip to content

Commit

Permalink
Create Reverse a doubly linked list
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored May 14, 2024
1 parent d187d17 commit ebb9f9c
Showing 1 changed file with 108 additions and 0 deletions.
108 changes: 108 additions & 0 deletions Reverse a doubly linked list
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
//Reverse a doubly linked list

import java.util.*;
import java.lang.*;
import java.io.*;

class Node {
int data;
Node next, prev;

Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}

class GFG {
public static void main(String args[])throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());

while(t-- > 0) {
int n = Integer.parseInt(read.readLine());
String str[] = read.readLine().trim().split(" ");
Node head = null, tail = null;

for(int i = 0; i < n; i++) {
int data = Integer.parseInt(str[i]);

if(head == null) {
head = new Node(data);
tail = head;
}
else {
tail.next = new Node(data);
tail.next.prev = tail;
tail = tail.next;
}
}

head = reverseDLL(head);

if(verify(head))
displayList(head);
else
System.out.print("Your pointers are not correctly connected");
System.out.println();
}
}

public static void displayList(Node head) {
while(head.next != null) {
System.out.print(head.data + " ");
head = head.next;
}

System.out.print(head.data);
}

class Node {
int data;
Node next, prev;

Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}

public static Node reverseDLL(Node head) {
Node temp = head;
Stack<Integer> st = new Stack<>();

while(temp != null) {
st.push(temp.data);
temp = temp.next;
}

temp = head;

while(!st.isEmpty()) {
temp.data = st.pop();
temp = temp.next;
}

return head;
}

public static boolean verify(Node head) {
int fl = 0;
int bl = 0;
Node temp=head;

while(temp.next!=null) {
temp = temp.next;
fl++;
}

while(temp.prev!=null) {
temp = temp.prev;
bl++;
}

return fl==bl;
}
}

0 comments on commit ebb9f9c

Please sign in to comment.