{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 스택, 큐" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "스택은 Last-In-First-Out (LIFO)\n", "\n", "큐는 First-In-First-Out (FIFO)\n", "\n", "파이썬에서 리스트는 큐와 스택의 모든 연산을 지원하지만 큐의 연산은 비효율적이다.\n", "\n", "따라서 Deque 를 이용하면 좋은 성능을 낼 수 있다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 스택\n", "\n", "- 스택은 다음과 같은 2가지 주요 연산을 지원하는 요소의 컬렉션으로 사용되는 추상 자료형이다.\n", " - push(): 요소를 컬렉션에 추가한다.\n", " - pop(): 아직 제거되지 않은 가장 최근에 삽입된 요소를 제거한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 연결 리스트를 이용한 스택 ADT 구현" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Node:\n", " def __init__(self, item, next):\n", " self.item = item\n", " self.next = next" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "class Stack:\n", " def __init__(self):\n", " self.last = None\n", " \n", " def push(self, item):\n", " self.last = Node(item, self.last)\n", " \n", " def pop(self):\n", " item = self.last.item\n", " self.last = self.last.next\n", " return item" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "stack = Stack()\n", "stack.push(1)\n", "stack.push(2)\n", "stack.push(3)\n", "stack.push(4)\n", "stack.push(5)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "4\n", "3\n", "2\n", "1\n" ] } ], "source": [ "for __ in range(5):\n", " print(stack.pop())" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 4 }