我在C ++中基本没有链接列表的问题,但出于某种原因,这是我的问题。我使用提供的包中的其他类打印出一个节点,但是当我继续使用时,我只是继续撞到墙上。
由于我修修补补,下面的代码是乱七八糟的。我不知道从哪里开始。截至目前,这是一个空指针异常。
仅供参考:poll()
只是移除当前头部并将其返回,offer()
正在添加到后方。截至目前,例外情况是在提供方法中oldLast.next = last
。
我不是要求任何人彻底解决这个问题。我只需要一些提示来进步。
public class FIFOQueue implements Queue {
//put your name as the value of the signature.
String signature = "name";
Node head = new Node(null);
Node pointer = head;
Node first;
Node last;
Node prev;
Node curr;
class Node {
Process process;
Node next;
Node(Process p) {
this.process = p;
this.next = null;
}
}
@Override
public void offer(Process p) {
if(head == null)
{
head = new Node(p);
first = head;
last = head;
}
else
{
Node oldLast = last;
Node newNode = new Node(p);
last = newNode;
oldLast.next = last;
}
}
@Override
public Process poll() {
if(isEmpty())
throw new NoSuchElementException();
Node oldPointer = first;
first = first.next;
head = first;
return oldPointer.process;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public String getSignature() {
return signature;
}
}
答案 0 :(得分:0)
我认为你的核心问题在于:
Node prev;
Node curr;
这些令你困惑。删除它们。
Node prev;
- 这应该在Node
类。Node curr;
- 这应该是局部变量,而不是实例变量。另外
Node head = new Node(null);
不会凝胶
if(head == null)
{
head = new Node(p);
要么head == null
表示列表是空的还是别的 - 但要保持一致。
答案 1 :(得分:0)
(代表OP发布)。
public void offer(Process p) {
if(head.process == null)
{
head = new Node(p);
first = head;
last = head;
}
last.next = new Node(p);
last = last.next;
}
这解决了我的问题。我不相信我让这让我感到困惑。