본문 바로가기
자료구조

배열을 이용한 스택(함수)

by mickey7 2023. 10. 10.

(python으로 구현)

# 스택의 데이터: 전역 변수
capacity = 10 #배열의 용량을 10으로 고정
array = [None] * capacity #스택의 요소들을 저장할 배열
top = -1	#상단의 인덱스(공백상태(-1)로 초기화)

#스택의 연산 : 일반 함수
def isEmpty() :
    if top == -1 : return True
    else : return False

def isFull() :
    return top == capacity-1

def push(e):
    global top
    if not isFull() :
        top += 1
        array[top] = e
    else:
        print("stack overflow")
        exit()

def pop():
    global top
    if not isEmpty():
        top -= 1
        return array[top+1]
    else:
        print("stack underflow")
        exit()

def peek():
    if not isEmpty():
        return array[top]
    else:pass

 

  • 데이터는 전역변수, 연산은 함수로 구현