具体思路是按顺序读取字符串,然后
对读取的字符执行相关操作:
将角色带入堆栈,直到正确
括号,然后在右括号之后
采取,它将不会被推入堆栈
堆栈执行取消堆栈操作,遇到
存储在数字堆栈中的数字,并遇到
运算符存储在符号堆栈中,直到左侧
括号被取出,操作结束。
然后,将数据放入数字堆栈中的堆栈中
依次取出,放入最终堆栈,
然后将符号堆栈中的所有数据放出
堆栈并存储在此堆栈中。然后阅读下
字符串的字符,直到结尾。此时,
最终堆栈的数据顺序取出并存储
在应用程序堆栈中,然后将
遍历应用程序堆栈以获得我们需要的结果。
public class InToSuf {
/*
* Create five characters,one is to retrieve data,one is to retrieve number, one
* is to retrieve character,one characters to retrieve the last data,the last is
* to output easily
*/
public static void main(String[] args) {
String arr = "(((1+((2+3)*4))-5)+4)";
StackTwo retrievedata = new StackTwo(2000);
StackTwo number = new StackTwo(2000);
StackTwo charcter = new StackTwo(2000);
StackTwo lastdata = new StackTwo(2000);
StackTwo output = new StackTwo(2000);
// define several data
int index = 0;
// change to 'char',make the expression is easy
char ch = ' ';
while (true) {
// get characters
ch = arr.substring(index, index + 1).charAt(0);
// judge the character and then perform related operators
if (retrievedata.isRight(ch))
{
while (true)
{
char a = retrievedata.outStack();
if (retrievedata.isLeft(a)) break;
if (retrievedata.ifOper(a)) charcter.push(a);
else number.push(a);
}
/*
* The purpose of these two methods is to use the two stacks as relay stations,
* placing numbers and characters on the other stack in order
*/
while (true)
{
if (number.isEmpty()) break;
char b = number.outStack();
lastdata.push(b);
}
while (true)
{
if (charcter.isEmpty()) break;
char c = charcter.outStack();
lastdata.push(c);
}
}
else retrievedata.push(ch);
index++;
if (index >= arr.length()) break; // judging the end of cycle
}
while (true) // Output characters in the required order
{
if (lastdata.isEmpty())
break;
char d = lastdata.outStack();
output.push(d);
}
output.showStack();
}
}
class StackTwo {
// Stack structure properties
private int maxSize;
private int top;
private char[] array;
// Initialize the stack structure
public StackTwo(int maxsize)
{
this.maxSize = maxsize;
this.top = -1;
array = new char[this.maxSize];
}
// Determine the stack is full
public boolean isFull()
{
return top == this.maxSize - 1;
}
// Determine the stack is empty
public boolean isEmpty()
{
return top == -1;
}
// Push
public void push(char arr)
{
if (isFull())
{
System.out.print("This stack is full!");
return;
}
top++;
array[top] = arr;
}
// Unstack
public char outStack()
{
if (isEmpty())
{
throw new RuntimeException();
}
char a = array[top];
top--;
return a;
}
public void showStack()
{
if (isEmpty())
{
System.out.print("this stack is empty.");
return;
}
while (true)
{
System.out.print(array[top] + "\t");
top--;
if (top == -1)
return;
}
}
// The purpose of this method is to determine whether it is parentheses.
public boolean isRight(char bracket)
{
return bracket == ')';
}
public boolean isLeft(char bracket)
{
return bracket == '(';
}
public boolean ifOper(char oper)
{
return oper == '+' || oper == '-' || oper == '*' || oper == '/';
}
}