「DA:stackqueue」の版間の差分

提供:classwiki
ナビゲーションに移動 検索に移動
111行目: 111行目:
   
   
  show()
  show()
= 括弧列の整合性をチェックするプログラム =
スタックを用いて実装します.
q = '(()(())())(()())'
stack = [0 for i in range(1000)]
cur = 0
for i in range(len(q)):
    if q[i] == '(':
        #### 埋めてください ####
    else:
        #### 埋めてください ####
# 括弧列が整合しているか判定
if #### 埋めてください #### :
    print('括弧列は整合しています.')
else:
    print('括弧列は整合していません!')

2025年4月15日 (火) 07:33時点における版

スタック

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(10)]
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():
    if head < tail:
        print(queue[head:tail])
    else:
        print(queue[head:] + queue[:tail])

# テストコード

queue = [0 for i in range(10)]
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(5): pop()

キーボード入力を受け取って最後の5行を表示させるプログラム

配列名はqueueのままですが,これはリングバッファです.リングバッファを操作する関数(push, pop, isEmpty, show)は省略しています.whileループの中の処理が未完成なので,完成させてください.

queue = [0 for i in range(5)] #最後の5行を表示させたい.
head = 0
tail = 0

while True:
    x = input()
    if x == 'end':
        break
    #### 完成させましょう ####

show()

括弧列の整合性をチェックするプログラム

スタックを用いて実装します.

q = '(()(())())(()())'

stack = [0 for i in range(1000)]
cur = 0

for i in range(len(q)):
    if q[i] == '(':
        #### 埋めてください ####
    else:
        #### 埋めてください ####

# 括弧列が整合しているか判定
if #### 埋めてください #### :
    print('括弧列は整合しています.')
else:
    print('括弧列は整合していません!')