进栈出栈代码java 进栈出栈代码c++版

java语言的完整进站出站程序楼主要的究竟是一个栈的程序,还是要一段能够实现中缀变成后缀的程序?我这里有一份作业 。也许你有用 。
文件CharStackD.java:
/**
* 用数组实现的栈 。能够设置栈所使用数组的大小
*/
public class CharStackD {
char[] ch;
int top;
//构造函数
public CharStackD() {
ch = new char[10];
int top = -1;
}
public CharStackD(int n) {
ch = new char[n];
int top = -1;
}
public CharStackD(char c) {
ch = new char[10];
int top = 0;
ch[top] = c;
}
public CharStackD(int n,char c) {
ch = new char[n];
int top = 0;
ch[top] = c;
}
//压栈
public boolean push(char c) {
top++;
if (top == ch.length)
return false;
ch[top] = c;
return true;
}
//出栈
public char pop() {
if (top == -1)
return ' ';
return ch[top--];
}
//查询栈是否为空
public boolean isEmpty() {
if (top == -1) return true;
return false;
}
//查询栈是否已满
public boolean isFull() {
if (top == ch.length) return true;
return false;
}
}
文件:ConvertMToB.java
/**
*此程序的功能是将中缀表达式转换成后缀表达式 。程序使用了一个堆栈 。转换
* 的方法:当读到字母时直接输出;当读到加减乘除号时,有三种情况,一是栈空,
【进栈出栈代码java 进栈出栈代码c++版】 * 将符号压入栈中,二是当前符号比栈顶的符号优先级低,将栈顶符号弹出并根据
* 当前符号与栈顶符号的情况决定下一步的操作,三是当前符号比栈顶的符号优先
* 级高,将当前符号压栈;遇到左括号入栈;遇到右括号将左右括号之间的符号全
* 部出栈,同时略去括号 。
*假定中缀表达式已经被事先存放于s1中 。
*/
public class ConvertMToB {
//事先存入的表达式
static String s1 = "a+b*(c/d)-e/f";
//主程序
public static void main(String arg[]) {
//s2用于输出结果
String s2 = "";
int current = 0;
CharStackD stack = new CharStackD();
char c;
//按字符扫描s1
while (currents1.length()) {
c = s1.charAt(current);
//扫描到字符,直接输出
if ((c = 'a')(c = 'z')) s2 += c;
//扫描到左括号,入栈
if (c == '(') stack.push(c);
//扫描到右括号,输出括号间的符号
if (c == ')') {
for(;;) {
char out = stack.pop();
if (out == '(') break;
else {
if (out == ' ') {
System.out.println("Wrong in " + s1);
System.exit(0);
}
s2 += out;
}
}
}
//扫描到加减乘除号
if ("+-*/".indexOf((int)c)-1) {
//栈空,入栈
if (stack.isEmpty()) {
stack.push(c);
current++;
continue;
}
//扫描到加减号
if ("+-".indexOf((int)c)-1) {
char topChar = stack.pop();
if (topChar == '(') stack.push(topChar);
for (int i = 0;i = 1;i++) {
if ("+-*/".indexOf((int)topChar)-1) s2 += topChar;
topChar = stack.pop();
if (topChar == '(') {
stack.push(topChar);
break;
}
}
stack.push(c);
}
//扫描到乘除号
else {
char topChar = stack.pop();
if (topChar == '(')
stack.push(topChar);
else {
if ("*/".indexOf((int)topChar)-1)
s2 += topChar;
else {
stack.push(topChar);
}
}
stack.push(c);
}
}
//扫描下一个字符
current++;
}
//清理栈内剩余的符号
while (!(stack.isEmpty())) {

推荐阅读