스택

킵고잉·2025년 1월 1일

-1) 스택 개념

스택 : 쌓는다 !
먼저 입력한 데이터를 제일 나중에 꺼낼 수 있는 자료구조 (FILO)
삽입하는 연산을 push, 꺼내는 연산을 pop

-2) 스택 정의

스택의 ADT

  1. push
  2. pop
  3. isFull
  4. isEmpty
  5. top : 최근에 삽입한 데이터의 위치 저장

스택 구현하기

최근에 삽입한 데이터를 대상으로 뭔가 연산을 해야할 때 스택 떠올리기
( 데이터를 그냥 저장하고 순서와 상관 없이 임의 접근하기만 해도 되면 배열 사용 )

stack=[]
max_size=10

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:
 		return stack.pop()

파이썬의 리스트는 크기를 동적으로 관리하기 댸문에 isFull() 과 isEmpty() 는 실제 문제를 풀 때 구현 x

stack=[]

def push(stack,item):
	stack.append(item)
    print("데이터가 추가되었습니다.")

def pop(stack):
	if len(stack)==0:
    	print("스택이 비어있습니다.")
        return None
 	else: 
    	return stack.pop()

append()와 pop()을 사용하는 것이니 push(), pop() 함수도 굳이 구현 필요 x

stack=[]

stack.append(1)
stack.append(2)
stack.append(3)

top_element=stack.pop() # 3
next_element=stack.pop() # 2

stack_size=len(stack)
profile
열심히 하면 되겠지

0개의 댓글