我正在做一个涉及链表的家庭作业。我们必须实现一个队列 ADT,而我遇到问题的一种方法是将一个节点添加到列表的末尾(入队方法)。这是我的代码:
公共类队列实现 QueueInterface {
private Node head;
private Node tail;
private int sz;
public Queue() {
head = null;
tail = null;
sz = 0;
}
public void enqueue(T newEntry) {
Node newElement = new Node(newEntry);
newElement.next = null;
tail.next = newElement;
tail = newElement;
}
public T dequeue() {
T result = null;
if(head != null) {
result = head.data;
head = head.next;
sz--;
}
return result;
}
public T getFront() {
return head.data;
}
public boolean isEmpty() {
if (head == null) {
return true;
}
return false;
}
public void clear() {
while (!isEmpty()) {
dequeue();
}
}
@Override
public String toString() {
return "Queue [head=" + head + ", sz=" + sz + "]";
}
public class Node {
private Node next;
private T data;
public Node (T newData) {
data = newData;
}
@Override
public String toString() {
return "Node [next=" + next + ", data=" + data + "]";
}
}
}
如果有人可以帮助我解决这个问题,我将非常感激。谢谢你的时间!:)