算法-第四版-練習1.3.29解答

題目

用環形鏈表實現Queue。環形鏈表也是一條鏈表,只是沒有任何結點鏈接爲空,且只要鏈表非空則last.next的值就爲first。只能使用一個Node類型的實例變量(last)。

思路

用last.next代替first即可。

代碼

package Chap1.$3;

import edu.princeton.cs.algs4.StdIn;

public class E29
{
    private class Node
    {
        Node next;
        int item;
    }

    private Node last;
    private int N = 0;

    public void en(int item)                                            ////⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️⬇️
    {
        Node oldlast = last;
        last=new Node();
        last.item = item;
        if (isEmpty()) last.next = last;
        else
        {
            last.next = oldlast.next;
            oldlast.next = last;
        }
        N++;
    }
    public int de()
    {
        int item = last.next.item;
        N--;
        if(isEmpty()) last =null;
        else
        {
            last.next = last.next.next;
        }
        return item;
    }                                                                   ////⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️⬆️
    public boolean isEmpty()
    {
        return N == 0;
    }
    public int size()
    {
        return size();
    }
    public static void main(String... args)
    {
        E29 e = new E29();
        while (!StdIn.isEmpty())
        {
            e.en(StdIn.readInt());
        }
        while (!e.isEmpty())
        {
            System.out.print(e.de());
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章