共計(jì) 544 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
要實(shí)現(xiàn)雙鏈表的倒序輸出,可以使用遞歸或者迭代的方式。
- 使用遞歸方式實(shí)現(xiàn)雙鏈表的倒序輸出:
public void reversePrint(Node node) {if (node == null) {return;
}
reversePrint(node.next);
System.out.print(node.data + " ");
}
- 使用迭代方式實(shí)現(xiàn)雙鏈表的倒序輸出:
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 + " ");
}
}
在上述代碼中,假設(shè)雙鏈表的節(jié)點(diǎn)類(lèi)為 Node
,包含數(shù)據(jù)域data
和指向下一個(gè)節(jié)點(diǎn)的引用next
,并且鏈表的頭節(jié)點(diǎn)為node
。使用遞歸方式時(shí),先遞歸調(diào)用reversePrint(node.next)
,然后再輸出當(dāng)前節(jié)點(diǎn)的數(shù)據(jù)域。使用迭代方式時(shí),先將鏈表的節(jié)點(diǎn)依次入棧,然后再依次出棧并輸出對(duì)應(yīng)的數(shù)據(jù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完