用java实现stack模板
栈是一种基于后进先出(LIFO)策略的线性数据结构。
这就像手枪弹夹一样,先填进去的子弹都打出,后填进去的子弹后打出。
该模板只有5个方法,分别是isEmpty(),size(),top(),pop(),push(T).
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class stack<Item> { private Node first; private int N; private class Node{ Item item; Node next; } public boolean isEmpty(){ return first ==null; } public int size(){ return N; } public void push(Item item){ Node oldfirst = first; first = new Node(); first.item = item; first.next = oldfirst; N++; } public Item pop(){ Item item = first.item; first = first.next; N--; return item; } public Item top(){ return first.item; }
public static void main(String[] args) { stack<Integer> te = new stack<Integer>(); te.push(19); if(te.isEmpty()){ System.out.println("isEmpty!"); }else System.out.println("Not Empty!"); te.push(20); System.out.println(te.pop()); System.out.println(te.top()); System.out.println(te.pop()); if(te.isEmpty()){ System.out.println("isEmpty!"); }else System.out.println("Not Empty!"); } }
|
该程序输入为:
1 2 3 4 5
| Not Empty! 20 19 19 isEmpty!
|
部分实现参考于算法(第四版)
v1.5.2