How to reverse a doubly linked list in Java?

To reverse a doubly linked list, you can follow these steps:

  1. Create a temporary variable temp to store the next node of the current node.
  2. Set the next node of the current node to point to the previous node, and set the previous node of the current node to point to temp.
  3. Set the current node as temp.
  4. Repeat steps 2 and 3 until the current node is null.
  5. Set the last node of the original linked list as the new head node.

Here is an example code:

class Node {
  int value;
  Node prev;
  Node next;
  
  public Node(int value) {
    this.value = value;
  }
}

public class DoublyLinkedList {
  private Node head;
  
  public void reverse() {
    Node current = head;
    Node temp = null;
    
    while (current != null) {
      temp = current.next;
      current.next = current.prev;
      current.prev = temp;
      current = temp;
    }
    
    if (temp != null) {
      head = temp.prev;
    }
  }
  
  // 添加其他方法和测试代码
}

In the above code, the reverse() method is used to reverse a doubly linked list. First, we start from the head node and traverse each node in the list one by one. During the traversal, we swap the pointers of the current node’s previous and next nodes, then set the current node as the next node, repeating this process until the current node is null. Finally, we set the last node of the original list as the new head node.

bannerAds