class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head =None
def push(self, value):
#new_head 라는 인스터스 변수 생성
new_head = Node(value)
#생성한 인스턴스변수인 new_head.next에
#현재 헤더를 넣어주는 이유는 스택의 경우
#pop시 head가 빠져나가는 형태로
#나중에 들어온 리스트가 먼저 빠져나가는것이 스택이니
#이제막 생성되는곳에 헤더위치를 넣어주기위해서 우선
#생성하는 리스트 다음 헤더를 지금 헤더의 위치로 넣은다음
#지금의 헤더를 새로생성한 리스트로 바꿔준다면 리스트 생성전 헤더는 생성한 리스트의 다음순서가되고 생성된 리스트가 맨위의 헤더를 가지게 됩니다
new_head.next = self.head
self.head = new_head
def pop(self):
#비어있으면 정지 해야하니 empty함수로 상황확인
if self.is_empty():
return "stack is empty"
#현재 헤더정보를 저장해서 돌려보내줘야하니 잠깐 저장해둘 delete_head변수에현재 head를 저장
delete_head = self.head
#현재 head를 삭제할것이니 .next를 이용하여 다음 헤더로 바꿔서 연결함
self.head = self.head.next
return delete_head
#peek꼭대기 녀석을 반환해주는함수
def peek(self):
if self.is_empty():
return "stack is empty"
#self.head만 보내면 위치정보만 뜨니 여기서 .data하던가 받는곳에서 .data를 하면된다
return self.head.data
def is_empty(self):
return self.head is None
stack =Stack()
stack.push(3)
print(stack.peek())
stack.push(4)
print(stack.peek())
print(stack.pop().data)
print(stack.peek())