Javaで双方向リンクリストを逆順に出力の方法
双方向リストを逆から出力するには、再帰またはイテレーションの方法を利用することができる。
- 双方向リストの値を再帰的に逆順に出力する
public void reversePrint(Node node) {
if (node == null) {
return;
}
reversePrint(node.next);
System.out.print(node.data + " ");
}
- イテレータを用いて双方向リストを逆順に出力する
public void reversePrint(Node node) {
Stack<Node> stack = new Stack<>();
Node current = node;
while (current != null) {
stack.push(current);
current = current.next;
}
while (!stack.isEmpty()) {
System.out.print(stack.pop().data + " ");
}
}
上で示したコードでは、双方向リストのノードのクラスが Node で、データ領域 data と次のノードへの参照 next を持ち、リストの先頭ノードが node と仮定する。再帰を利用する場合、最初に再帰的に reversePrint(node.next) を呼び出し、その後、現在のノードのデータ領域を出力する。反復を利用する場合、最初にリストのノードを順番にスタックに押し込み、その後、順番に出力して対応するデータを出力する。