實現棧操做的接口:java
Stack.javacode
package com.wanali.java_ds.sqstack; public interface Stack { public void clear(); public boolean empty();//判斷棧是否爲空 public int length();//求棧的長度 public Object peek();// 取得棧頂元素 public void push(Object x);// 向棧頂添加元素 public Object pop();// 刪除並返回棧頂元素 public void display();//打印棧中元素 }
SqStack.java接口
package com.wanali.java_ds.sqstack; public class SqStack implements Stack { private Object[] elem; private int top; public SqStack(int maxsize) { top = 0; elem = new Object[maxsize]; } public void clear() { // TODO Auto-generated method stub while (top != 0) { elem[top] = null; top--; } } public boolean empty() { // TODO Auto-generated method stub return top == 0; } public int length() { // TODO Auto-generated method stub int i = 0; while (top != 0) { i++; --top; } return i; } public Object peek() { // TODO Auto-generated method stub return elem[top - 1]; } public void push(Object x) { // TODO Auto-generated method stub elem[top] = x; top++; } public Object pop() { // TODO Auto-generated method stub return elem[--top]; } public void display() { for (int i = top - 1; i >= 0; i--) { System.out.println(elem[i]); } } }
TestSqStack.java圖片
package com.wanali.java_ds.sqstack; public class TestSqStack { public static void main(String[] args) { SqStack stack = new SqStack(10); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.display(); System.out.println("判斷棧是否爲空:"); System.out.println(stack.empty()); System.out.println("刪除棧頂元素:"); stack.pop(); stack.display(); System.out.println("取棧頂元素:"+"\n"+stack.peek()); System.out.println("棧的長度爲:" + "\n" + stack.length()); System.out.println("調用clear方法清空棧:"); stack.clear(); stack.display(); System.out.println("棧已被清空!!"); System.out.println("判斷棧是否爲空:"); System.out.println(stack.empty()); } }
運行結果以下:it