Reverse a Doubly Linked List GFG problem
Given a doubly linked list. Your task is to reverse the doubly linked list and return its head.
Examples:
Input: LinkedList: 3 <-> 4 <-> 5
Output: 5 <-> 4 <-> 3
Input: LinkedList: 75 <-> 122 <-> 59 <-> 196
Output: 196 <-> 59 <-> 122 <-> 75
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
//{ Driver Code Starts
import java.io.*;
import java.util.*;
class DLLNode {
int data;
DLLNode next;
DLLNode prev;
DLLNode(int val) {
data = val;
next = null;
prev = null;
}
}
public class Main {
// Function to insert a node at the end of the Doubly Linked List
public static void push(DLLNode tail, int new_data) {
DLLNode newNode = new DLLNode(new_data);
newNode.next = null;
newNode.prev = tail;
if (tail != null) {
tail.next = newNode;
}
}
// Function to print nodes in a given doubly linked list
public static void printList(DLLNode head) {
if (head == null) {
return;
}
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
// Main driver function
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
String[] arr = br.readLine().trim().split(" ");
DLLNode head = new DLLNode(Integer.parseInt(arr[0]));
DLLNode tail = head;
for (int i = 1; i < arr.length; i++) {
push(tail, Integer.parseInt(arr[i]));
tail = tail.next;
}
Solution obj = new Solution();
head = obj.reverseDLL(head);
printList(head);
}
}
// Verifying the doubly linked list
public static boolean verify(DLLNode head) {
int forwardLength = 0;
int backwardLength = 0;
DLLNode temp = head;
while (temp.next != null) {
temp = temp.next;
forwardLength++;
}
while (temp.prev != null) {
temp = temp.prev;
backwardLength++;
}
return forwardLength == backwardLength;
}
}
// } Driver Code Ends
/*
class DLLNode {
int data;
DLLNode next;
DLLNode prev;
DLLNode(int val) {
data = val;
next = null;
prev = null;
}
}
*/
class Solution {
public DLLNode reverseDLL(DLLNode head) {
// Your code here
if (head == null) return null;
DLLNode current = head;
DLLNode temp = null;
// Swap next and prev for each node
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
// Move to the next node (which is actually the previous node)
head = current; // Keep track of last processed node
current = current.prev;
}
return head; // New head of reversed DLL
}
}
Comments
Post a Comment