一维数组模拟数据结构-------栈
Posted StanLong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一维数组模拟数据结构-------栈相关的知识,希望对你有一定的参考价值。
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() throws Stack1OperationException{ 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+"]"; } }
以上是关于一维数组模拟数据结构-------栈的主要内容,如果未能解决你的问题,请参考以下文章