老师,为什么这个把tail给head后,head还是空啊
public class LinkedListQueue<E> implements Queue<E> {
@Override
public int getSize() {
return size;
}
@Override
public void enQueue(E e) {
if (tail == null) {
tail = new Node(e);
head = tail;
} else {
tail.next = new Node(e);
tail = tail.next;
}
size++;
}
@Override
public E deQueue() {
if (size == 0) {
throw new IllegalArgumentException("deQueue failed.The queue is empty");
}
Node retNode = head;
head = head.next;
retNode.next = null;
if (head == null) {
tail = null;
}
size--;
return retNode.e;
}
@Override
public E getHead() {
if (size == 0) {
throw new IllegalArgumentException("getHead failed.The queue is null");
}
return head.e;
}
@Override
public E getTail() {
return tail.e;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("队首");
Node cur = head;
while (head != null) {
builder.append("<-" + head.e);
head = head.next;
}
builder.append("<-队尾");
return builder.toString();
}
@Override
public boolean isEmpty() {
return size == 0;
}
private class Node {
public E e;
public Node next;
public Node() {
}
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this(e, null);
}
@Override
public String toString() {
return this.e.toString();
}
}
private int size;
private Node head;
private Node tail;
public LinkedListQueue() {
}
}
49
收起
正在回答
1回答
如果真的执行到了你蓝框的语句,head 不应该为空了。
如果你测试 head 为空,要么根本没有执行这句;要么后续的逻辑又把 head 给修改了。
实际使用你的测试用例一步一步调试跟踪一下,看到底在哪里,你的 head 变成空了?
继续加油!:)
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星