젊은이의 블로그

[자료구조와알고리즘with파이썬] Ch.01-2 배열 구조로 스택 구현하기 본문

책/자료구조와알고리즘with파이썬

[자료구조와알고리즘with파이썬] Ch.01-2 배열 구조로 스택 구현하기

젊은사람 등장 2024. 9. 24. 10:17

 

배열구조

array[ ] 스택 요소들을 저장할 배열
capacity 스택의 최대 용량. 저장할 수 있는 요소의 최대 개수(상수)
top 상단 요소의 위치(변수, 인덱스)

*top은 -1로 초기화함

-> 맨 처음에는 스택이 비어있음 + 배열은 0번부터 시작함

 

[isEmpty( ), isFull( )]

det isEmpty( ):
	if top ==-1 : return True
    else : return False
    
def ifFull( ): return top==capacity

 

[push(e)]

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

 

[pop( )]

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

 

[peek( )]

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

 

[size( )]

def size(): return top+1

 


근데 이렇게 하면 배열을 한 프로그램 당 하나만 사용할 수 있음

-> 그래서 객체지향 프로그래밍이 필요함 (클래스 사용)

class ArrayStack //원하는 클래스 이름으로 바꿀 수 있음
	def __init__(self,capacity): //self는 파이썬 클래스 멤버함수의 첫 번째 매개변수임
    	self.capacity = capacity
        self.array = [None]*self.capacity
        self.top = -1