포시코딩

2월19일 - Queue, Stack, Linked List 구현하기 (Python) 본문

TIL

2월19일 - Queue, Stack, Linked List 구현하기 (Python)

포시 2023. 2. 20. 03:33
728x90

Queue

FIFO

queue = []

def enqueue(data):
    queue.append(data)

def dequeue():
    data = queue[0]
    del queue[0]
    return data

for i in range(1, 10):
    enqueue(i)

print(queue)
print('dequeue: ', dequeue())
print('dequeue: ', dequeue())
print(queue)

 

Stack

LIFO

stack = []

def push(data):
    stack.append(data)

def pop():
    data = stack[-1]
    del stack[-1]
    return data

for i in range(1, 10):
    push(i)

print(stack)
print('pop: ', pop())
print('pop: ', pop())
print(stack)

 

Linked List

class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

node1 = Node(1)
head = node1

def add(data):
    node = head
    while node.next:
        node = node.next
    node.next = Node(data)

for i in range(2, 10):
    add(i)

node = head
while node.next:
    print(node.data)
    node = node.next
print(node.data)

 

복습복습

728x90