要反转一个双向链表,可以按照以下步骤进行操作:
创建一个临时变量temp,用于保存当前节点的下一个节点。将当前节点的下一个节点指向前一个节点,将当前节点的前一个节点指向temp。将当前节点设为temp。重复步骤2和3,直到当前节点为null。将原链表的最后一个节点设为新的头节点。下面是一个示例代码:
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; } } // 添加其他方法和测试代码}
在上述代码中,reverse()
方法用于反转双向链表。首先,我们从头节点开始,依次遍历链表中的每个节点。在遍历的过程中,我们交换当前节点的前后指针,然后将当前节点设为下一个节点,重复这个过程直到当前节点为null。最后,我们将原链表的最后一个节点设为新的头节点。