栈是一种后进先出的数据结构,想象成一个 杯子,后面放进去的东西在上面,会被先取出来
以下是用java 数组实现的简单的栈
public class Stack {
private int top;
private int maxSize;
private char[] elements;
public Stack(int maxSize) {
this.maxSize = maxSize;
elements = new char[maxSize];
this.top = -1;
}
public void push(char i) {
if (top == maxSize - 1) {
throw new RuntimeException("stack is full");
}
elements[++top] = i;
}
public char pop() {
if (top == -1) {
throw new RuntimeException("stack is empty");
}
return elements[top--];
}
public char peek() {
return elements[top];
}
public boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
Stack stack=new Stack(10);
stack.push('a');
stack.push('b');
stack.push('c');
System.out.println(stack.isEmpty());
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
//System.out.println(stack.pop()); throw Exception
}
}
上面使用栈的数据结果 放入 abc, 打印出来的是 cba,所以,此处使用栈 实现 字符串反转
下面使用 栈 实现简单的 括号匹配 的校验,匹配 {} [] ()
定义一个括号校验器
class BracketCheck{
private String content;
public BracketCheck(String content){
this.content=content;
}
public void check(){
Stack stack=new Stack(content.length());
for(int i=0;i<content.length();i++){
char ch=content.charAt(i);
switch(ch){
case '{':;
case '[':;
case '(':
stack.push(ch);
break;
case '}':;
case ']':;
case ')':
if(!stack.isEmpty()){
if( (ch=='}' && stack.pop()!='{') ||
(ch==']' && stack.pop()!='[') ||
(ch==')' && stack.pop()!='(') ){
throw new RuntimeException("check error");
}
break;
}
throw new RuntimeException("check error");
default:
break;
}
}
if(!stack.isEmpty()){
throw new RuntimeException("check error");
}
}
}
以下代码会验证成功
BracketCheck bc=new BracketCheck("{hello world[ni hao a](你呢)}");
bc.check();
System.out.println("check success");
如果去掉最右边的大括号,会抛出异常