Java數據結構——棧(Stack)

棧是Vector的一個子類,它實現了一個標準的後進先出的棧
堆棧只定義了默認構造函數,用來創建一個空棧。堆棧除了包括Vector定義的所有方法,也定義了自己的一些方法。
棧構造函數

Stack()		//創建默認棧

棧的額外方法

序號 方法 描述
1 boolean empty() 測試堆棧是否爲空。
2 Object peek( ) 查看堆棧頂部的對象,但不從堆棧中移除它。
3 Object pop( ) 移除堆棧頂部的對象,並作爲此函數的值返回該對象。
4 Object push(Object element) 把項壓入堆棧頂部。
5 int search(Object element) 返回對象在堆棧中的位置,以 1 爲基數。

實例

import java.util.*;
 
public class StackDemo {
 
 	//壓入並輸出
    static void showpush(Stack<Integer> st, int a) {
        st.push(new Integer(a));
        System.out.println("push(" + a + ")");
        System.out.println("stack: " + st);
    }
 
 	//彈出並輸出
    static void showpop(Stack<Integer> st) {
        System.out.print("pop -> ");
        Integer a = (Integer) st.pop();
        System.out.println(a);
        System.out.println("stack: " + st);
    }
 
    public static void main(String args[]) {
        Stack<Integer> st = new Stack<Integer>();	//創建棧對象,並實例化,棧類型爲int
        System.out.println("stack: " + st);
        showpush(st, 42);
        showpush(st, 66);
        showpush(st, 99);
        showpop(st);
        showpop(st);
        showpop(st);
        try {
            showpop(st);
        } catch (EmptyStackException e) {
            System.out.println("empty stack");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章