栈的执行顺序是后进先出的,本例子是用数组模拟栈的执行顺序
Stack.java
//用数组模拟栈
class Stack{
//数组
Object[] elements;
//指向上一个的帧
int index;
//默认为5
Stack(){
this(5);
}
Stack(int max){
elements=new Object[max];
}
//压栈,入栈
public void push(Object element)throws StackOprationException{
if(index==elements.length){
throw new StackOprationException("栈已满!");
}
elements[index++]=element;
}
//弹栈,出栈
public Object pop()throws StackOprationException{
if(index==0){
throw new StackOprationException("栈已空!");
}
return elements[--index];
}
}
StackOprationException.java
public class StackOprationException extends Exception {
public StackOprationException(){}
public StackOprationException(String msg){
super(msg);
}
}
Test.Java
class Tset{
public static void main(String[] args){
Stack s=new Stack();
User u1=new User("张三",20);
User u2=new User("李四",21);
User u3=new User("王五",22);
User u4=new User("赵六",23);
User u5=new User("美灯",24);
//入栈
try{
s.push(u1);
s.push(u2);
s.push(u3);
s.push(u4);
s.push(u5);
s.push(u5);
}catch(StackOprationException e){
e.printStackTrace();
}
//出栈
try{
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}catch(StackOprationException e){
e.printStackTrace();
}
}
}
class User{
String name;
int age;
public User(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "User[name="+name+",age="+age+"]";
}
}
希望大家互相学习{:soso_e113:},代码见附件。{:soso_e181:}
|
|