Skip to content

Instantly share code, notes, and snippets.

@thmain
Created November 26, 2023 04:26
Show Gist options
  • Save thmain/fb2bb84939e66921349adbebb193c1c0 to your computer and use it in GitHub Desktop.
Save thmain/fb2bb84939e66921349adbebb193c1c0 to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class ReverseDLL {
static class Node{
int data;
Node prev;
Node next;
public Node(int data){
this.data = data;
}
}
public static Node[] reverse(Node head){
Node newHead = null;
Node current = null;
Node prev = null;
Stack<Node> stack = new Stack<>();
while(head!=null){
stack.push(head);
head = head.next;
}
while (!stack.isEmpty()){
Node x = stack.pop();
x.next = null;
x.prev = null;
if(newHead==null){
newHead = x;
current = x;
}else{
if(prev==null)
prev = newHead;
current.next = x;
current = current.next;
current.prev = prev;
prev = current;
}
}
return new Node []{newHead, current};
}
public static void print(Node head){
while(head!=null){
System.out.print("<->" + head.data);
head= head.next;
}
System.out.println();
}
public static void printBack(Node tail){
while(tail!=null){
System.out.print("<->" + tail.data);
tail= tail.prev;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
Node one = new Node(2);
Node two = new Node(3);
Node three = new Node(4);
Node four = new Node(5);
head.next = one;
one.prev = head;
one.next = two;
two.prev = one;
two.next = three;
three.prev = two;
three.next = four;
four.prev = three;
System.out.println("Original List print forward");
print(head);
System.out.println("Original List print backward");
printBack(four);
System.out.println("----------------------------");
Node [] nodes = reverse(head);
System.out.println("Reversed List print forward");
print(nodes[0]);
System.out.println("Reversed List print backward");
printBack(nodes[1]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment