Untitled
unknown
plain_text
a year ago
957 B
7
Indexable
class DoublyListNode {
int val;
DoublyListNode prev, next;
DoublyListNode(int val) {
this.val = val;
this.prev = null;
this.next = null;
}
}
public class ReverseDoublyLinkedList {
// Reverse a Doubly Linked List
public DoublyListNode reverseDLL(DoublyListNode head) {
if (head == null) return null; // If the list is empty
DoublyListNode current = head;
DoublyListNode temp = null;
// Swap next and prev for all nodes
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev; // Move to the next node (which is prev after the swap)
}
// After the loop, temp points to the last node, which becomes the new head
if (temp != null) {
head = temp.prev; // Update head to the new head
}
return head;
}Editor is loading...
Leave a Comment