package Main; import java.util.Scanner; import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction; /*栈操作*/
public class Main{
public int maxsize;
public int top;
private Object[] stackelem;
//初始化
public Main(int maxstack)
{
top = 0;
this.maxsize = maxstack;
stackelem = new Object[maxstack];
}
//将栈置空
public void clear()
{
top = 0;
}
//判断栈是否为空
public boolean isEmpty()
{
if(top==0)
return true;
return false;
}
//入栈
public void push(Object x) throws Exception
{
if(top==maxsize)
throw new Exception("the stack is enough");
stackelem[top] = x;
top++;
}
//从顶端开始输出所有栈内内容
public void print() {
for(int i=top-1;i>=0;i--)
{
System.out.println(stackelem[i]);
}
}
//出栈
public Object pop() throws Exception
{
if(isEmpty())
throw new Exception("the stack is empty!");
top--;
return stackelem[top];
}
public static void main(String[] args) throws Exception {
Main aStack = new Main(100);
Scanner aScanner = new Scanner(System.in);
String aString = aScanner.nextLine();
char []a = new char[aString.length()];
a = aString.toCharArray();
Main bStack = new Main(100);
for(int i=0;i<a.length;i++)
{
aStack.push(a[i]);
}
int flag=1;
char pop;
for(int i=0;i<a.length;i++)
{
pop = (char) aStack.pop();
if(pop==')')
{
bStack.push(pop);
}else if(pop=='('&&bStack.isEmpty()){
flag = 0; }else if(pop=='(')
{
bStack.pop();
}
}
if (bStack.isEmpty()&&flag==1) {
System.out.println("The String is right!");
}else {
System.out.println("the string is wrong!");
}
aStack.print(); }
}
使用java实现栈的操作,同时加入了括号匹配实现应用;
括号匹配:
(1)将所有输入的字符串压入栈中
(2)依次取出,遇到‘)’,则将其压入新栈中。
(3)遇到‘(’,则从新栈中取出与之匹配,判断最后栈是否为空;
(4)需要注意的是,第一个括号为反的情况,设置标志位flag用于判断。