亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java堆棧類使用實(shí)例(java中stack的使用方法)

 更新時間:2013年12月19日 17:06:11   作者:  
java中stack的使用方法,堆棧是一種"后進(jìn)先出"(LIFO) 的數(shù)據(jù)結(jié)構(gòu), 只能在一端進(jìn)行插入(稱為"壓棧") 或刪除 (稱為"出棧")數(shù)據(jù)的操作,下面看示例吧

JAVA 中,使用 java.util.Stack 類的構(gòu)造方法創(chuàng)建對象。

 public class Stack extends vector

 構(gòu)造方法 : public Stack() 創(chuàng)建一個空 Stack。

方法:  1. public push  (item )  把項(xiàng) 壓入棧頂。其作用與 addElement (item ) 相同。

參數(shù) item 壓入棧頂?shù)捻?xiàng) 。 返回: item 參數(shù) ;

2. public pop () 移除棧頂對象,并作為函數(shù)的值 返回該對象。

返回:棧頂對象(Vector 對象的中的最后一項(xiàng))。

拋出異常 : EmptyStackException 如果堆棧式空的 。。。

3. public peek() 查看棧頂對象而不移除它。。

返回:棧頂對象(Vector 對象的中的最后一項(xiàng))。

拋出異常 : EmptyStackException 如果堆棧式空的 。。。

4. public boolean empty (測試堆棧是否為空。)  當(dāng)且僅當(dāng)堆棧中不含任何項(xiàng)時 返回 true,否則 返回 false.

5. public int search  (object o)  返回對象在堆棧中位置, 以 1 為基數(shù), 如果對象 o是棧中的一項(xiàng),該方法返回距離 棧頂最近的出現(xiàn)位置到棧頂?shù)木嚯x; 棧中最上端項(xiàng)的距離為?。薄?。 使用equals 方法比較 o 與 堆棧中的項(xiàng)。。。  

參數(shù): o 目標(biāo)對象;

復(fù)制代碼 代碼如下:

/**
 * @author yuanLi
 */
package thinkingJava;
import java.util.*;

import com.sun.org.apache.bcel.internal.generic.NEW;
/**
 *
 */
public class StackTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Stack stack = new Stack(); // 創(chuàng)建堆棧對象
        System.out.println("11111, absdder, 29999.3 三個元素入棧");
        stack.push(new Integer(11111)); //向 棧中 壓入整數(shù) 11111
        printStack(stack);  //顯示棧中的所有元素

        stack.push("absdder"); //向 棧中 壓入
        printStack(stack);  //顯示棧中的所有元素

        stack.push(new Double(29999.3)); //向 棧中 壓入
        printStack(stack);  //顯示棧中的所有元素

        String s = new String("absdder");
        System.out.println("元素absdder在堆棧的位置"+stack.search(s));     
        System.out.println("元素11111在堆棧的位置"+stack.search(11111));

        System.out.println("11111, absdder, 29999.3 三個元素出棧"); //彈出 棧頂元素
        System.out.println("元素"+stack.pop()+"出棧");
        printStack(stack);  //顯示棧中的所有元素
        System.out.println("元素"+stack.pop()+"出棧");
        printStack(stack);  //顯示棧中的所有元素
        System.out.println("元素"+stack.pop()+"出棧");
        printStack(stack);  //顯示棧中的所有元素

 
    }

    private static void printStack(Stack<Integer> stack ){
        if (stack.empty())
            System.out.println("堆棧是空的,沒有元素");
            else {
                System.out.print("堆棧中的元素:");
                Enumeration items = stack.elements(); // 得到 stack 中的枚舉對象
                while (items.hasMoreElements()) //顯示枚舉(stack ) 中的所有元素
                    System.out.print(items.nextElement()+" ");
            }
        System.out.println(); //換行
    }
}

相關(guān)文章

最新評論