首先写两个栈的异常类,分别是栈满和栈空的类:
package com.jim.stack;
public class ExceptionStackEmpty extends RuntimeException{
public ExceptionStackEmpty(String err){
System.out.println(err);
}
}
package com.jim.stack;
public class ExceptionStackFull extends RuntimeException {
public ExceptionStackFull(String err){
System.out.println(err);
}
}
然后编写栈的接口,规定栈的五个基本方法的格式,参数等:
package com.jim.stack;
public interface Stack {
public int getSize();
public boolean isEmpty();
public Object top() throws ExceptionStackEmpty;
public void push(Object ele)throws ExceptionStackFull;
public Object pop() throws ExceptionStackEmpty;
}
然后写栈的实现(数组的方法):
package com.jim.stack.impl;
import com.jim.stack.ExceptionStackEmpty;
import com.jim.stack.ExceptionStackFull;
import com.jim.stack.Stack;
public class Stack_Array implements Stack {
public static final int CAPACITY = 1024;
private int capacity;
private Object[] obj;
private int top = -1;
public Stack_Array(){
this(CAPACITY);
}
public Stack_Array(int capacity2) {
capacity = capacity2;
obj = new Object[capacity];
}
@Override
public int getSize() {
return top+1;
}
@Override
public boolean isEmpty() {
return (top < 0);
}
@Override
public Object pop() throws ExceptionStackEmpty {
Object ele;
if(this.isEmpty())
throw new ExceptionStackEmpty("异常:栈为空");
ele = obj[this.top];
obj[top] = null;
top--;
return ele;
}
@Override
public void push(Object ele) throws ExceptionStackFull{
if(this.getSize() == CAPACITY)
throw new ExceptionStackFull("异常:栈满");
top++;
obj[top] = ele;
}
@Override
public Object top() throws ExceptionStackEmpty {
if(this.isEmpty())
throw new ExceptionStackEmpty("异常:栈空");
return obj[this.top];
}
}
下面是测试栈的应用:
包括数组的倒序和一些编译器常用的检查符号配对的方法:
package com.jim.test;
import com.jim.stack.impl.Stack_Array;
public class Test {
public static Integer[] reverse(Integer[] a) {
Stack_Array s = new Stack_Array(a.length);
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++)
s.push(a[i]);
for (int i = 0; i < b.length; i++)
b[i] = (Integer) s.pop();
return b;
}
public static void matches(String str){
char c[] = str.toCharArray();
Stack_Array s = new Stack_Array(c.length);
for(int i = 0;i < c.length;i++){
if(c[i] == '('){
s.push(c[i]);
}else if(c[i] == ')'){
s.pop();
}
}
if(s.isEmpty()){
System.out.println("配对");
}else{
System.out.println("不配对");
}
}
/*public static void main(String[] args) {
Integer[] a = new Integer[5];
Integer[] b = new Integer[a.length];
for (int i = 0; i < a.length; i++)
a[i] = i;
System.out.println("交换顺序之前:");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
b = reverse(a);
System.out.println();
System.out.println("交换顺序之后:");
for (int i = 0; i < a.length; i++)
System.out.print(b[i] + " ");
}*/
public static void main(String[] args) {
String str = "78+89*45/(89+(45-96)+45";
matches(str);
}
}
转载于:https://blog.51cto.com/ywj852752270/1286639