简介:栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。
特性:先进后出
元素操作:入栈(push),出栈(pop),查栈顶元素(peek),检查栈空(isEmpty),检查栈满(isFull);
栈的理解:如果说,我们把栈比作一个一定容量的数组,则top永远指向数组的末尾,每次入栈操作即将top+1,然后存入入栈的值;相反的,每次出栈操作即将返回当前top所在的元素值,然后令top-1;查看栈顶元素则是返回top所在下标的值,top本身不进行任何操作;栈空,则top指向数组最小下标的越界,top值为-1;栈满则top == arr.lenth() – 1;
java代码栈的实现与分隔符的匹配:
public class StackX {
private int maxSize; //栈的最大空间容量
private char[] stackArray; //入栈的数组元素
private int top; //栈顶下标索引
public StackX(int s) { //栈的构造器
maxSize = s;
stackArray = new char[maxSize];
top = -1; //空栈
}
//push 入栈操作
public void push(char j) {
stackArray[++top] = j;
}
//pop 出栈操作
public char pop() {
return stackArray[top–];
}
//查值操作
public char peek() {
return stackArray[top];
}
//查空栈
public boolean isEmpty() {
return (top == -1);
}
//查满栈
public boolean isFull() {
return (top == (maxSize-1));
}
}
public class BracketChecker {
//用栈来匹配分隔符
private String input;
public BracketChecker(String in) {
input = in;
}
public void check(){
int maxSize = input.length(); //获取输入字符串的长度
StackX myStackX = new StackX(maxSize); //建栈
for(int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
switch (ch) {
case ‘{‘:
case ‘[‘:
case ‘(‘:
myStackX.push(ch);
break;
case ‘}’:
case ‘]’:
case ‘)’:
if (!myStackX.isEmpty()) {
char chx = myStackX.pop();
if ((ch == ‘}’ && chx != ‘{‘) ||
(ch == ‘]’ && chx != ‘[‘) ||
(ch == ‘)’ && chx != ‘(‘)) {
System.out.println(“Error at ” + (i+1) + ” char”);
}
}else {
System.out.println(“Empty Stack”);
}
break;
default:
break;
}
}
if (!myStackX.isEmpty()) {
System.out.println(“右分隔符出现错误”);
}
}
}
public class Main{
//栈
public static void main(String[] args) throws IOException {
String input;
while(true) {
System.out.println(“请输入包含分割符的字符串:”);
System.out.flush();
input = getString();
if (input.equals(“”)) {
break;
}
BracketChecker bracketChecker = new BracketChecker(input);
bracketChecker.check();
}
}
public static String getString() throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String s = bufferedReader.readLine();
return s;
}
}
喜欢的打个关注哦。谢谢大家