一維數組模擬數據結構-------棧
阿新 • • 發佈:2017-10-22
user smi for return dex element spa ack []
1、用一維數據模擬棧結構
public class Stack1{ //一維數據模擬棧結構 Object[] elements; //默認棧的容量為5 public Stack1(){ this(5); //this 這裏是代碼的重用,也可以寫成 elements = new Object[5]; } public Stack1(int max){ elements = new Object[max]; } //模擬棧指針int index; //壓棧方法 public void push(Object element) throws Stack1OperationException{ if(index == elements.length){ throw new Stack1OperationException("The Stack1 have been Full"); } elements[index++] = element; } //彈棧方法 public Object pop() throwsStack1OperationException{ if(index == 0){ throw new Stack1OperationException("The Stack1 have been Empty!"); } return elements[--index]; } }
2、自定義棧異常類
public class Stack1OperationException extends Exception{ public void Stack1OperationException(){ };public Stack1OperationException(String msg){ super(msg); } }
3、測試
public class TestStack1{ public static void main(String[] args){ Stack1 s = new Stack1(); User u1 = new User("Jack",23); User u2 = new User("Ford",24); User u3 = new User("King",25); User u4 = new User("Smith",26); User u5 = new User("COOK",27); User u6 = new User("zhangsan",28); try{ s.push(u1); s.push(u2); s.push(u3); s.push(u4); s.push(u5); s.push(u6); }catch(Stack1OperationException 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()); }catch(Stack1OperationException e){ e.printStackTrace(); } } } class User{ String name; int age; User(String name, int age){ this.name = name; this.age = age; } public String toString(){ return "User[name="+name+" ,age="+age+"]"; } }
一維數組模擬數據結構-------棧