java写遍历stack
时间: 2023-06-06 18:06:02 浏览: 53
Sure, 我可以帮你解决这个问题。下面是一个示例代码段,用于遍历Java Stack。
```
import java.util.Stack;
public class StackTraversal {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// push some elements onto the stack
stack.push("Hello");
stack.push("World");
stack.push("!");
// loop through the stack and print out each element
while(!stack.empty()) {
System.out.println(stack.pop());
}
}
}
```
这段代码首先创建了一个 `Stack` 对象,然后将三个字符串 `"Hello"`, `"World"`, `"!"` 分别压入栈中。接下来,使用 `while` 循环来遍历栈,并输出每个元素。注意,使用 `pop` 方法可以取出栈中最上面的元素。
希望这可以帮助到你!
相关问题
java二叉树遍历怎么写
Java二叉树遍历可以使用递归或非递归的方式实现。
1. 递归遍历:
前序遍历:
```java
public void preOrder(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}
```
中序遍历:
```java
public void inOrder(TreeNode root) {
if (root != null) {
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
}
```
后序遍历:
```java
public void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
}
```
2. 非递归遍历:
前序遍历:
```java
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.print(node.val + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
}
```
中序遍历:
```java
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
System.out.print(node.val + " ");
node = node.right;
}
}
```
后序遍历:
```java
public void postOrder(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()) {
TreeNode node = stack1.pop();
stack2.push(node);
if (node.left != null) {
stack1.push(node.left);
}
if (node.right != null) {
stack1.push(node.right);
}
}
while (!stack2.isEmpty()) {
System.out.print(stack2.pop().val + " ");
}
}
```
用java写中序遍历算法
下面是使用Java编写的二叉树中序遍历算法:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class InorderTraversal {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}
```
在这个算法中,我们使用了一个栈来存储节点。首先将根节点压入栈中,然后将其所有左子结点压入栈中,取出栈顶节点,保存节点值,再将当前指针移到其右子节点上,若存在右子节点,则将右子节点压入栈中,若不存在,则取出栈顶节点,再处理栈顶节点的右子节点。