我在读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;
}
}
我没有改写他们在我的方式是这样的:
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;
}
我在出队右做()和排队()方法?
在main方法,我应该这样做:
public static void main(String[] args) {
QueueOfStrings q = new QueueOfStrings();
q.enqueue("roro");
q.enqueue("didi");
q.enqueue("lala");
System.out.println(q.dequeue());
}
感谢
是什么意思为 “我做的出队))写(和排队(方法是什么?” ? - 另外,你的最后一个if应该是if(first == null && last == null){而不是if(first = last = null){ – matt
我的意思是对的..我在其他代码中发现它们有时使用'first = last = null' – Joe
这甚至没有编译。你想用first = last = null做什么? –