這篇文章的内容是受Vaidehi Joshi的“排隊或不排隊” 以及Base CS系列視訊堆棧和隊列的啟發
在Vaidehi的文章中,她解釋了隊列如何工作并顯示了一些使隊列入隊和出隊的“函數/方法”,這是一個簡單直接的示例,向您展示了它在PHP中的工作方式(我假設您已經了解了CS視訊)。
PHP帶有一個稱為的标準庫SplQueue(Spl表示标準PHP庫)SplQueue繼承自SplDoublyLinkedList。是以,SplQueue支援方法push()和對象pop()。但是請注意,如果在對象上使用push()和pop()方法SplQueue,則其行為類似于堆棧而不是隊列
Manu Manjunath (PHP官方文檔的原始解釋)
簡短的長篇小說,SplDoublyLinkedList意味着同一個圖書館可同時為queue和使用stacks。
堆棧
如上所述,如果在對象上使用push()和pop(),SplQueue則行為将是堆棧而不是隊列,請參見:$stack = new SplQueue();
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->pop(); // remove the last one
print_r($stack);
請注意,彈出了3個而不是 1。
s列
方法使用SplQueue的隊列是:enqueue()和dequeue(),請參閱:$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');
$queue->dequeue(); // remove the first one
print_r($q);
Queue和Stack輔助方法:$queue->enqueue('dev'); // or $stack->push('dev');
$queue->enqueue('.to'); // or $stack->push('.to');
$queue->count(); // (int) 2
$queue->isEmpty(); // false
$queue->valid(); // false because right now the pointer is in the last position
// move the cursor to the first position, if you run valid() again after this it will be true
$queue->rewind();
$queue->current(); // "dev", current() just work if you rewind() before call it
$queue->unshift(3); // add the value to the beginning
$queue->current(); // "dev", because we need to move the cursor back to the first position
$queue->rewind();
$queue->current(); // 3
$queue->add(2, 'random-text'); // Add/insert a new value at the specified index
print_r($queue); // Show only 3, "dev" and "to" because we don't rewind() yet.
$queue->rewind(); // move the cursor back to the first position
print_r($queue);
周遊隊列和堆棧:$queue = new SplQueue();
$queue->enqueue('dev');
$queue->enqueue('.to');
$queue->unshift('https://');
$queue->rewind(); // always rewind the queue/stack, so PHP can start from the beginning.
while($queue->valid()){
echo $queue->current()."\n"; // Show the first one
$queue->next(); // move the cursor to the next element
}
您可以使用很多方法,但我無法在此處顯示所有方法,您可以在官方文檔中檢視有關SplQueue
那麼,您現在正在使用哪種程式設計語言?是否具有内置的隊列和堆棧?如果是這樣,我該如何使用?如果不是,您該怎麼做?寫一篇文章,向我們展示如何使用您喜歡的程式設計語言處理隊列和堆棧!?