class Node { char data; Node next; public Node(char data) { this.data = data; next = null; } } class LinkStack { Node first; public LinkStack() { first = null; } public boolean isEmpty() { return first == null; } public boolean push(Node node) { node.next = first; first = node; return true; } public Node pop() { if (isEmpty()) return null; Node tmp; tmp = first; first = first.next; return tmp; } } public class ReverseStack { public static void main(String[] args) { LinkStack stackIn = new LinkStack(); LinkStack stackOut = new LinkStack(); String str = "hello world!"; char[] a = str.toCharArray(); Node node = new Node(' '); stackIn.push(node); for (char x : a) { Node n = new Node(x); stackIn.push(n); } while (stackIn.first != null) { stackOut.push(stackIn.pop()); if (stackOut.first.data == ' ') { while (stackOut.first != null) System.out.print(stackOut.pop().data); } } } }
java栈的反转,java实现栈的反转
最新推荐文章于 2023-09-24 07:51:08 发布
本文介绍了一种使用两个栈实现字符串逆序输出的方法。通过定义节点类和链栈类,文章详细展示了如何将输入字符串逐字符压入栈中,再通过另一个栈进行逆序输出的过程。此方法适用于需要逆序处理数据的场景。
663

被折叠的 条评论
为什么被折叠?



