import java.util.Stack;
public class UsingStack {
public static void main(String[] args) {
//構造棧對象,使用類型限制,只能存儲Integer數據
Stack<Integer> s = new Stack<Integer>();
//1、2、3依次入棧
s.push(1);
s.push(2);
s.push(3);
//3、2、1依次出棧
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}
//這是我寫的順序結構的棧
import java.util.EmptyStackException;
import java.util.Vector;
public class UsingStack{
public static void main(String[] args){
//構造棧對象,使用類型限制,只能存儲Integer數據
MyStack<Integer> s = new MyStack<Integer>();
//1、2、3依次入棧
s.push(1);
s.push(2);
s.push(3);
//3、2、1依次出棧
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}
/**
* 棧類
* @author developer_05
* @param <T>
*/
class MyStack<T> extends Vector<T>{
/**
* 構造方法
*/
public MyStack(){
}
/**
* 入棧方法
* @param item 待入棧的元素
* @return 返回入棧的元素
*/
public T push(T item) {
addElement(item);
return item;
}
/**
* 出棧方法(同步處理)
* @return 返回出棧元素
*/
public synchronized T pop() {
T obj;
int len = size();
if (len == 0)
throw new EmptyStackException();
obj = elementAt(len - 1);
removeElementAt(len - 1);
return obj;
}
/**
* 判斷棧是否為空的方法
* @return 返回true(棧空)或false(棧非空)
*/
public boolean empty() {
return size() == 0;
}
private static final long serialVersionUID = 1L;
}