老师,为什么这个把tail给head后,head还是空啊

来源:1-7 带有尾指针的链表:使用链表实现队列

wukai001

2021-01-30 16:33:29

http://img.mukewang.com/climg/601519b609a0865608110395.jpg

​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() {

}

}


写回答

1回答

liuyubobobo

2021-01-30

如果真的执行到了你蓝框的语句,head 不应该为空了。


如果你测试 head 为空,要么根本没有执行这句;要么后续的逻辑又把 head 给修改了。


实际使用你的测试用例一步一步调试跟踪一下,看到底在哪里,你的 head 变成空了?


继续加油!:)

2
hukai001
回复
hiuyubobobo
hp>谢谢老师解答,解决了?

h021-01-30
共8条回复

算法与数据结构

波波老师5年集大成之作,算法与数据结构系统学习,考试、面试、竞赛通用

2638 学习 · 1091 问题

查看课程