「DA:stackqueue」の版間の差分
ナビゲーションに移動
検索に移動
(→スタック) |
(→キュー) |
||
| 47行目: | 47行目: | ||
= キュー = | = キュー = | ||
def isEmpty(): | |||
if head + 1 == tail: | |||
print('キューは空です!') | |||
return True | |||
return False | |||
def push(x): | |||
global tail | |||
if tail == len(queue): | |||
print('これ以上要素を追加できません!') | |||
return | |||
queue[tail] = x | |||
tail += 1 | |||
def pop(): | |||
global head | |||
if isEmpty(): | |||
return | |||
head += 1 | |||
return queue[head-1] | |||
def show(): | |||
print(queue[head:tail]) | |||
# テストコード | |||
queue = [0 for i in range(100)] | |||
head = 0 | |||
tail = 0 | |||
push(1) | |||
push(1) | |||
push(2) | |||
push(3) | |||
push(5) | |||
push(8) | |||
push(13) | |||
push(21) | |||
show() | |||
for i in range(5): pop() | |||
show() | |||
for i in range(10): pop() | |||
2025年4月15日 (火) 06:17時点における版
スタック
def isEmpty():
if cur == 0:
print('スタックは空です!')
return True
return False
def push(x):
global cur
if cur == len(stack):
print('これ以上要素を追加できません!')
return
stack[cur] = x
cur += 1
def pop():
global cur
if isEmpty():
return
cur -= 1
return stack[cur]
def show():
print(stack[:cur])
# テストコード
stack = [0 for i in range(100)]
cur = 0
push(1)
push(1)
push(2)
push(3)
push(5)
push(8)
push(13)
push(21)
show()
for i in range(5): pop()
show()
for i in range(5): pop()
キュー
def isEmpty():
if head + 1 == tail:
print('キューは空です!')
return True
return False
def push(x):
global tail
if tail == len(queue):
print('これ以上要素を追加できません!')
return
queue[tail] = x
tail += 1
def pop():
global head
if isEmpty():
return
head += 1
return queue[head-1]
def show():
print(queue[head:tail])
# テストコード
queue = [0 for i in range(100)]
head = 0
tail = 0
push(1)
push(1)
push(2)
push(3)
push(5)
push(8)
push(13)
push(21)
show()
for i in range(5): pop()
show()
for i in range(10): pop()