首页 技术 正文
技术 2022年11月9日
0 收藏 513 点赞 4,288 浏览 1414 个字
 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用于判断。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,488
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289