我剛剛創建了排隊,排隊和peek方法,但我不知道他們是否在O(1)時間。如果不是,我該怎麼做,並且你能解釋如何在O(1)時間內做到這一點嗎?隊列<T> O(1)時間
Node<T> start;
public void enqueue(T val)
{
Node<T> n = new Node<T>(val);
if (start == null)
{
start = n;
} else
{
n.next = start;
start = n;
}
}
public T dequeue()
{
if (start != null)
{
T item = start.nodeValue;
start = start.next;
return item;
}
return null;
}
public void peek()
{
Node<T> curr = start;
while (curr != null)
{
System.out.print(curr.nodeValue + " ");
curr = curr.next;
}
}
我忽略了'peek()'方法。這個答案是正確的。 – shmosel