如题
由数组构成的顺序栈:
public class Array_Stack { int[] a=new int[10]; int p=-1; public boolean isEmpty() { boolean b=false; if(p==-1) { b=true; } return b; } public boolean isFull() { boolean b=false; if(p==9) { b=true; } return b; } public void push(int x) { if(isFull()) { System.out.println("Statck is full!"); } else { p++; a[p]=x; } } public int pop() { if(isEmpty()) { System.out.println("Statck is empty!"); return -1; } else { return a[p--]; } } }
由链表构成的链式栈:
public class Linked_Stack { int v; Linked_Stack next; public Linked_Stack() { } public Linked_Stack(int x) { v=x; } public boolean isEmpty() { return next==null; } public void push(int x) { Linked_Stack p; p=this.next; next=new Linked_Stack(x); next.next=p; } public int pop() { int x; if(!isEmpty()) { x=next.v; next=next.next; } else { x=-1; System.out.println("Linked_Stack is empty!"); } return x; } }
调用:
public class c1 { public static void main(String[] args) { //顺序栈 Array_Stack myas = new Array_Stack(); int t; for (int i = 1; i <= 15; i++) { myas.push(i); } for (int i = 1; i <= 15; i++) { t = myas.pop(); if (t != -1) { System.out.print(t + "\t"); } } //链式栈 Linked_Stack myls=new Linked_Stack(); for (int i = 1; i <= 12; i++) { myls.push(i); } for (int i = 1; i <= 15; i++) { t = myls.pop(); if (t != -1) { System.out.print(t + "\t"); } } } }
执行结果:
Statck is full! Statck is full! Statck is full! Statck is full! Statck is full! 10 9 8 7 6 5 4 3 2 1 Statck is empty! Statck is empty! Statck is empty! Statck is empty! Statck is empty! 12 11 10 9 8 7 6 5 4 3 2 1 Linked_Stack is empty! Linked_Stack is empty! Linked_Stack is empty!
请注意:顺序栈中对栈顶的描述和书上略有不同。编程看思想,没有一定之规。
Java自带的Stack简单用法:
public static void main(String[] args) { // TODO Auto-generated method stub int t; Stack<Integer> myls = new Stack<Integer>(); for (int i = 1; i <= 12; i++) { myls.push(i); } System.out.println(myls.peek()); System.out.println(myls.size()); for (int i = 1; i <= 15; i++) { if (!myls.empty()) { t = myls.pop(); System.out.print(t + "\t"); } else { System.out.println("Stack is empty."); } } }