鏈式佇列—用連結串列來實現佇列

Coderzhuzeyu發表於2020-12-10

鏈式佇列(先進先出)
用連結串列來實現佇列
在這裡插入圖片描述

class Node {
    public int data;
    public Node next;
    //每次new一個節點  就要呼叫它的構造方法
    public Node(int data) {
        this.data = data;
    }
}
public class MyQueue {
    public int usedSize;
    public Node front;//佇列的頭
    public Node rear;//佇列的尾
    public boolean offer(int val) {//放資料
        Node node = new Node(val);
        if (rear == null) {//第一次插入
            this.rear = node;
            this.front = node;
        }else {
            this.rear.next = node;
            this.rear = node;
        }
        usedSize++;//每存一個元素  usedSize++
        return true;
    }
    //出隊且刪除隊頭元素
    public int poll() {
        if (isEmpty()) {
           throw new RuntimeException("佇列為空!");
        }
        int data = this.front.data;
        this.front = this.front.next;
        return data;

    }
    public boolean isEmpty() {
        return this.usedSize == 0;
    }
    //檢視隊頭元素
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("佇列為空!");
        }
        return this.front.data;
    }




public class TestDemo {
    public static void main(String[] args) {
        MyQueue myQueue =new MyQueue();
        myQueue.offer(1);
        myQueue.offer(2);
        myQueue.offer(3);
        System.out.println(myQueue.peek());//1
        System.out.println(myQueue.poll());//1
        System.out.println(myQueue.peek());//2

相關文章