스택구조
가장 먼저 넣은 것이 가장 나중에 나가는 구조
스택 생성
stack = [None, None, None, None, None]
top = -1
데이터 삽입: push
stack = [None, None, None, None, None]
top = -1
top += 1
stack[top] = '커피'
top += 1
stack[top] = '녹차'
top += 1
stack[top] = '꿀물'
print('스택 상태')
for i in range(len(stack) - 1, -1, -1) : #맨위에서부터 출력
print(stack[i])
스택 상태
None
None
꿀물
녹차
커피
데이터 추출: pop
stack = ['커피', '녹차', '꿀물', None, None, None]
top = 2
print('스택 상태')
for i in range(len(stack) - 1, -1, -1) :
print(stack[i])
print('----------------')
data = stack[top]
stack[top] = None
top -= 1
print('pop', data)
data = stack[top]
stack[top] = None
top -= 1
print('pop', data)
data = stack[top]
stack[top] = None
top -= 1
print('pop', data)
print('-----------------')
print('스택 상태')
for i in range(len(stack) - 1, -1, -1) :
print(stack[i])
스택 상태
None
None
None
꿀물
녹차
커피
----------------
pop 꿀물
pop 녹차
pop 커피
-----------------
스택 상태
None
None
None
None
None
None
스택 초기화
사이즈가 큰 스택에서는 일일이 None 값을 입력할 수 없다.
size 값만 변경하면 원하는 크기의 빈 스택이 생성되게 만들어야 한다.
size = 5 #스택의 크기
stack = [None for i _in range(size)]
top = -1
스택이 꽉 찼는지 확인
if (top값 == 스택크기 -1) :
스택이 꽉 참
스택이 꽉 찼는지 확인 하는 함수
def isStackFull() :
global SIZE, stack, top
if (top >= SIZE - 1):
return True
else :
return False
SIZE = 5
stack = ['커피', '녹차', '꿀물', '콜라', '환타']
top = 4
print('스택이 꽉 찼는지 여부', isStackFull())
스택이 꽉 찼는지 여부 True
스택에 데이터를 삽입하는 함수
def isStackFull() :
global SIZE, stack, top
if (top >= SIZE - 1):
return True
else :
return False
def push(data) :
global SIZE, stack, top
if (isStackFull()) :
print('스택이 꽉 찼습니다.')
return
top += 1
stack[top] = data
SIZE = 5
stack = ['커피', '녹차', '꿀물', '콜라', None]
top = 3
print(stack)
push('환타')
print(stack)
push('게토레이')
['커피', '녹차', '꿀물', '콜라', None]
['커피', '녹차', '꿀물', '콜라', '환타']
스택이 꽉 찼습니다.
스택이 비었는지 확인하는 함수
def isStackEmpty() :
global SIZE, stack, top
if (top == -1) :
return True
else :
return False
SIZE = 5
stack = [None for _ in range(SIZE)]
top = -1
print('스택이 비었는지 여부', isStackEmpty())
스택이 비었는지 여부 True
스택에서 데이터를 추출하는 함수
def isStackEmpty() :
global SIZE, stack, top
if (top == -1) :
return True
else :
return False
def pop() :
global SIZE, stack, top
if (isStackEmpty()) :
print('스택이 비었습니다.')
return None
data = stack[top]
stack[top] = None
top -= 1
return data
SIZE = 5
stack = ['커피', None, None, None, None]
top = 0
print(stack)
retData = pop()
print('추출한 데이터', retData)
print(stack)
retData = pop()
['커피', None, None, None, None]
추출한 데이터 커피
[None, None, None, None, None]
스택이 비었습니다.