11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

listをstack/queueとして利用する

Posted at

はじめに

先日こちらを投稿しましたが、改めてstackとqueue(キューと読みます)について記載します。

stackとqueueについて

データの保存と取り扱いの方法のことを言います。
stackもqueueもデータを一列に並べますが、データの追加と取り出し方法にそれぞれ特徴があります。

stack

listのメソッドを使えば、簡単にlistをstackとして使えます。
stackでは最後に追加された要素が最初に取り出されます ("last-in, first-out")。

stackの一番上に要素を追加する(データを積む)にはappend()を使い,一番上から要素を取り出すにはpop()をに使います。

>> stack = ["chiba","tokyo","saitama","kanagawa"]
>>> stack.append("ibaraki")#追加
>>> stack.pop()#取り出し
'ibaraki'
>>> stack 
['chiba', 'tokyo', 'saitama', 'kanagawa']
>>> stack.pop()#取り出し
'kanagawa'
>>> stack
['chiba', 'tokyo', 'saitama']

queueとして使う

queueの場合、最初に追加した要素を最初に取り出します ("first-in, first-out")。
append()やpop()はlistの末尾に対して行うのは速いですが、先頭に対して行う場合には、他の要素をひとつずつずらす必要がある為、遅くなってしまいます。
そこでqueueの実装にはcollectionsのdequeを使用します。※dequeのappend、popはスレッドセーフ(並行処理されることを考慮してる)らしいです

>>> from collections import deque
>>> queue = deque(['chiba', 'tokyo', 'saitama'])

>>> queue.append("kanagawa")#追加
>>> queue 
deque(['chiba', 'tokyo', 'saitama', 'kanagawa'])
>>> queue.popleft()#取り出し
'chiba'
>>> queue
deque(['tokyo', 'saitama', 'kanagawa'])
>>> queue.popleft() #取り出し
'tokyo'
>>> queue
deque(['saitama', 'kanagawa'])

おわり

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?