我在讀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做什麼? –