java 队列实现中的 dequeue 和 enqueue 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40912280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:33:50 来源:igfitidea点击:
dequeue and enqueue methods in queue implementation
提问by Joe
I was reading about queues in java implementation. I found the following code
我正在阅读有关 Java 实现中的队列的信息。我找到了以下代码
public class QueueOfStrings {
private Node first = null; // least-recently added
private Node last = null; // most-recently added
private class Node {
private String item;
private Node next;
}
// is the queue empty?
public boolean isEmpty() {
return first == null;
}
public String dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue underflow");
}
String item = first.item;
first = first.next;
return item;
}
public void enqueue(String item) {
Node x = new Node();
x.item = item;
if (isEmpty()) {
first = x;
last = x;
} else {
last.next = x;
last = x;
}
}
I did rewrite them in my way like this:
我确实像这样以我的方式重写了它们:
public String dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue underflow");
} else if (first = last) {
String f = first.item;
first = null;
last = null;
return f;
}
String f = first.item;
first = first.next;
return f;
}
public void enqueue(String item) {
Node x = new Node(item);
if (first = last = null) {
first = last = x;
}
last.next = x;
last = x;
}
Am I doing right in dequeue() and enqueue() methods?
我在 dequeue() 和 enqueue() 方法中做得对吗?
In the main method should I do like this:
在主要方法中,我应该这样做:
public static void main(String[] args) {
QueueOfStrings q = new QueueOfStrings();
q.enqueue("roro");
q.enqueue("didi");
q.enqueue("lala");
System.out.println(q.dequeue());
}
Thanks
谢谢
采纳答案by sonnet
public String dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue underflow");
} else if (first == last) {
String f = first.item;
first = null;
last = null;
return f;
}
String f = first.item;
first = first.next;
return f;
}
public void enqueue(String item) {
Node x = new Node(item);
if (first == null && last == null) {
first = x;
last = x;
return; // return back when first node is enqueued
}
last.next = x;
last = x;
}