ํ์ชฝ ๋์์๋ง ์์๋ฅผ ๋ฃ๊ฑฐ๋ ๋บ ์ ์๋ ์๋ฃ๊ตฌ์กฐ.
๊ตฌ์กฐ์ ์ผ๋ก ๋จผ์ ๋ค์ด๊ฐ ์์๊ฐ ์ ์ผ ๋์ค์ ๋์ค๋๋ฐ ์ด๋ฅผ FILO(First In Last Out) ์๋ฃ๊ตฌ์กฐ๋ผ๊ณ ํ๋ค.
ํ๋ ๋ฑ๋ ํน์ ์์น์์๋ง ์์๋ฅผ ๋ฃ๊ฑฐ๋ ๋นผ๊ธฐ ๋๋ฌธ์ ์ธ ๊ฐ๋ฅผ ๋ฌถ์ด์ Restricted Structur๋ผ๊ณ ๋ถ๋ฅด๊ธฐ๋ ํ๋ค.
stack=[]
MAX_SIZE=10
pos=0
def top(stack):
return stack[pos-1]
def isFull(stack):
return len(stack)==MAX_SIZE
def isEmpty(stack):
return len(stack)==0
def push(stack,item):
if isFull(stack):
print("์คํ์ด ๊ฐ๋ ์ฐผ์ต๋๋ค.")
else:
stack.append(item)
print("๋ฐ์ดํฐ ์ถ๊ฐ")
def pop(stack):
if isEmpty(stack):
print('์คํ์ด ๋น์ด์์ต๋๋ค.')
return None
else:
print(f'{top(stack)}์ด ๋๊ฐ์ง๋๋ค.')
return stack.pop()
# ์คํ์ ๋ฐ์ดํฐ ์ถ๊ฐ
stack.append(1)
stack.append(2)
stack.append(3)
# ์คํ์์ ๋ฐ์ดํฐ ๊บผ๋
top_element = stack.pop( )
next_element = stack.pop( )
# ์คํ์ ํฌ๊ธฐ๋ฅผ ๊ตฌํจ
stack_size = len(stack)
print(stack)
์ฌ์ค ๊ตณ์ด push,pop ๊ตฌํ ์ํ๊ณ append,pop์จ๋ ๋๊ธด ํ๋ค.
import sys
stack=[]
def top(stack):
if len(stack) == 0:
return print(-1)
else:
return print(stack[-1])
def empty(stack):
if len(stack)==0:
return print(1)
else:
return print(0)
def push(stack,item):
stack.append(item)
def size(stack):
return print(len(stack))
def pop(stack):
if len(stack) == 0:
return print(-1)
else:
return print(stack.pop())
N=int(sys.stdin.readline())
for _ in range(N):
a=sys.stdin.readline().split()
if a[0]=='push':
push(stack,a[1])
elif a[0]=='pop':
pop(stack)
elif a[0]=='size':
size(stack)
elif a[0]=='empty':
empty(stack)
elif a[0]=='top':
top(stack)
์๊พธ ํ๋์ฉ ๋นผ๋จน์ด์ ๋ฐํ์์๋ฌ๊ฐ ๋จ๋ ์ฃผ์ํ์