1. 程式人生 > >Java中的Stack類和Queue介面

Java中的Stack類和Queue介面

前言

今天做劍指offer,裡面有道題要求用兩個棧實現一個佇列,之前也零零散散遇到過一些需要用到棧和佇列的資料結構的題目,於是抽空總結一下,不對之處望指出。

Stack類

Stack類繼承自Vector類,有以下幾個方法。
這裡寫圖片描述
1. boolean empty()
判斷棧是否為空
2. E peek()
返回棧頂物件,不移除
3. E pop()
返回棧頂物件,並移除
4. E push(E item)
壓入棧頂
5. int search(Object o)
返回物件在棧的位置

search方法測試

因為平時沒怎麼用過search方法,於是編寫一段小程式測試一下它的功能,如下。

import java.util.Stack;

public class StackDemo {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println("1在棧中的位置: " + stack.search
(1)); System.out.println("2在棧中的位置: " + stack.search(2)); System.out.println("3在棧中的位置: " + stack.search(3)); System.out.println("4在棧中的位置: " + stack.search(4)); stack.pop(); stack.pop(); System.out.println("4在棧中的位置: " + stack.search(4)); System.out
.println("3在棧中的位置: " + stack.search(3)); } }

輸出結果如圖
這裡寫圖片描述
由輸出知,search返回的位置是從棧頂開始計數,棧頂為1,而不在棧中的元素返回-1,所以我們可以通過返回值來判斷棧中是否存在我們要搜尋的元素。
最後,官方給出的API中推薦使用Deque介面來實現棧

Queue介面

Queue介面定義瞭如下6個方法,我們常用的LinkedList類就實現了Queue介面。
這裡寫圖片描述
1. boolean add(E e)
向佇列中新增元素
2. E element()
返回佇列的頭,且不移除
3. boolean offer(E e)
向佇列中新增元素
4. E peek()
返回佇列的頭,且不移除
5. E poll()
返回佇列的頭,且移除
6. E remove()
返回佇列的頭,且移除
add、element、remove會在操作失敗時丟擲異常,而offer、peek、poll在操作失敗時返回特殊值。
測試程式碼如下

import java.util.LinkedList;
import java.util.Queue;

public class QueueDemo {

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        System.out.println("目前是空佇列,返回的佇列頭是:" + queue.poll());
        // queue.remove();
        System.out.println("--------------");
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        System.out.println("使用peek方法,返回的結果是:" + queue.peek());
        System.out.println("使用poll方法,返回的結果是:" + queue.poll());
        System.out.println("使用poll方法後,再使用peek方法看佇列頭,返回的結果是:" + queue.peek());
    }

}

結果如圖
這裡寫圖片描述

參考