共計 612 個字符,預計需要花費 2 分鐘才能閱讀完成。
要反轉一個雙向鏈表,可以按照以下步驟進行操作:
- 創建一個臨時變量 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。最后,我們將原鏈表的最后一個節點設為新的頭節點。
丸趣 TV 網 – 提供最優質的資源集合!
正文完