利用数据结构中的栈实现单词的反转
程序员文章站
2022-07-02 17:11:00
...
package com.javaeye.liubey.algorithm.stack; import javax.swing.JOptionPane; import org.lx.print.P; /** * 项目名称:algorithm * 包名称:com.javaeye.liubey.algorithm.stack * 类名称:ReverseWord.java * 描述:反转输入的单词 * 创建人:Eason.Lau * 创建时间:2010-7-16 下午03:20:46 * Copyright http://liubey.iteye.com/ * @version * */ public class ReverseWord { public static void main(String[] args) { String input; String output = ""; StackChar stackChar; input = JOptionPane.showInputDialog("请输入需要转换的单词!"); if(input !=null && !input.equalsIgnoreCase("")) { stackChar = new StackChar(input.length()); //把单词push进栈中 for(int i=0;i<=input.length()-1;i++) { char temp = input.charAt(i); stackChar.push(temp); } //把单词取出 while(!stackChar.isEmpty()) { output = output + stackChar.pop(); } } P.printlnByMyself("输入单词为", input); P.printlnByMyself("单词反转为", output); } } class StackChar { private int maxSize;//最大容量 private char[] arrayStack; private int top;//栈顶 public StackChar(int n) { maxSize = n; arrayStack = new char[maxSize]; top = -1; } //入栈 public void push(char j) { arrayStack[++top] = j; } //出栈 public char pop() { return arrayStack[top--]; } //查看 public char view() { return arrayStack[top]; } //栈是否是空 public boolean isEmpty() { return (top == -1); } }