[공부] 내일배움캠프 알고리즘 3주차 Stack

Asher Park·2022년 11월 27일
2
post-thumbnail

스택(Stack) 이란?

  • 한쪽 끝으로만 자료를 넣고 뺄 수 있는 자료구조
  • Last In First Out
  • 넣은 순서를 기억하고 사용할 때 필요
  • 링크드 리스트와 유사하게 구현할 수 있다

push

def push(self, value):
        
        new_head = Node(value)
        new_head.next = self.head
        self.head = new_head

        return
  1. 새로운 값을 담은 노드를 만든다
  2. 새로운 노드의 next에 현재의 head 노드를 연결
  3. 새로운 노드를 head로 지정

pop

def pop(self):
        if self.is_empty():
            return "Stack is Empty"
            
        delete_node = self.head
        self.head = self.head.next

        return delete_node
  1. 제거할 노드를 변수에 잡아둔다
  2. head가 현재 head의 다음 노드를 가리키게 한다
  3. 제거할 노드를 반환한다

peek

def peek(self):
        if self.is_empty():
            return "Stack is Empty"

        return self.head.data
  1. 제일 위에 있는 노드를 반환

is_empty

def is_empty(self):
        
        return self.head is None
  1. head가 None인지 아닌지만 체크
profile
배움에는 끝이없다

0개의 댓글