标签:imp last next -- temp use bool private ble
question:
write a queue implementation that uses a cicular linked list, which is the same as a linked list except that no links are nul and the value of last.next is first whenever the list is not empty. keep only one node instance variable(last).
answer:
import edu.princeton.cs.algs4.*; public class Queue<Item> { private Node last = null; private int n = 0; private class Node { Item item; Node next; } public boolean isempty() { return last == null; } public int size() { return n; } public void enqueue(Item item) { if(last == null) { last = new Node(); last.item = item; last.next = last;//形成循环 n++; return; } Node node = new Node(); node.item = item; node.next = last.next; last.next = node; last = node;//注意,刚进入队列的才是队尾 n++; StdOut.println("last " + last.item); return; } public Item dequeue()//先进先出 { if(this.isempty()) { return null; } if(this.size() == 1) { Item item = last.item; last = null; n--; return item; } Node current = last.next.next; Node temp = last.next; last.next = current; n--; return temp.item; } public static void main(String[] args) { Queue<String> queue = new Queue<String>(); int size = queue.size(); StdOut.println("the size is " + size); while(!StdIn.isEmpty())//CTRL + d在linux下终止输入 { String item = StdIn.readString(); if(!item.equals("-")) { queue.enqueue(item); } else if(!queue.isempty()) { StdOut.print(queue.dequeue() + " "); } } StdOut.println(queue.size() + " left on the queue"); } }
标签:imp last next -- temp use bool private ble
原文地址:https://www.cnblogs.com/w-j-c/p/9060532.html