我有一个项目要求我们使用链表堆栈(NodeStack
)和队列(NodeQueue
)。我有以下示例代码:
class Node
{
object value;
Node next;
public void setValue(object o)
{
value = o;
}
public object getValue()
{
return value;
}
public void setNext(Node o)
{
next = o;
}
public Node getNext()
{
return next;
}
}
class NodeStack
{
Node top;
int count;
public void Push(object o)
{
Node newTop = new Node();
newTop.setValue(o);
newTop.setNext(top);
top = newTop;
count = count + 1;
}
public object Pop()
{
object value = top.getValue();
top = top.getNext();
return value;
}
public object Peek()
{
return top.getValue();
}
public void Clear()
{
top = null;
count = 0;
}
public int Count()
{
return count;
}
}
通过此代码,我应该能够将NodeStack
推导为NodeQueue
,但我无法理解Enqueue
和Dequeue
方法的语法。当我运行一个简单的enqueue和dequeue程序时,我在dequeue方法的第一行得到一个Null引用异常。真的很感激帮助。
我到目前为止的代码:
class NodeQueue
{
Node tail;
Node head;
int count;
public void Enqueue(object o)
{
if (head == null)
{
Node newHead = new Node();
newHead.setValue(o);
head = tail = newHead;
newHead.setNext(tail);
}
else
{
Node newTail = new Node();
newTail.setValue(o);
newTail.setNext(tail);
tail = newTail;
}
count++;
}
public object Dequeue()
{
object value = head.getValue();
head = head.getNext();
return value;
}
public void Clear()
{
head = null;
tail = null;
count = 0;
}
public int Count()
{
return count;
}
}
编辑:
已经处理了NullException的问题,但现在我遇到了dequeue问题。我正在使用这个程序来测试队列
NodeQueue nq = new NodeQueue();
nq.Enqueue(1);
nq.Enqueue(2);
nq.Enqueue(3);
nq.Enqueue(4);
nq.Enqueue(5);
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.WriteLine(nq.Dequeue());
Console.ReadLine();
预期输出为1..5。发生的输出是1继续打印。
答案 0 :(得分:1)
您的Enqueue
方法不正确,这就是为什么您在'Dequeue`中获得异常的原因
同样在Dequeue
中,您应该将计数减少一个。
您的Enqueue
head
未设置。
class NodeQueue
{
Node tail;
Node head;
int count;
public void Enqueue(object o)
{
if (head == null)
{
Node newHead = new Node();
newHead.setValue(o);
head = tail = newHead;
}
else
{
Node newTail = new Node();
newTail.setValue(o);
tail.setNext(newTail);
tail = newTail;
}
count++;
}
public object Dequeue()
{
if (null != head)
{
object value = head.getValue();
head = head.getNext();
count--;
return value;
}
return null;
}
public void Clear()
{
head = null;
tail = null;
count = 0;
}
public int Count()
{
return count;
}
}