linked list를 이용한 stack 구현

  • LIFO(Last In First Out) 구조를 생각하면서 구현하도록 한다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    class Node:
    def __init__(self, data=None):
    self.__data = data
    self.__next = None

    @property
    def data(self):
    return self.__data

    @data.setter
    def data(self, data):
    self.__data = data

    @property
    def next(self):
    return self.__next

    @next.setter
    def next(self, n):
    self.__next = n


    class LStack:
    def __init__(self):
    self.top = None

    def empty(self):
    if self.top is None:
    return True
    else:
    return False

    def push(self, data):
    new_node = Node(data)

    new_node.next = self.top
    self.top = new_node

    def pop(self):
    if self.empty():
    return

    cur = self.top
    self.top = self.top.next

    return cur.data

    def peek(self):
    if self.empty():
    return

    return self.top.data


    if __name__ == '__main__':

    s = LStack()

    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    s.push(5)

    while not s.empty():
    print(s.pop(), end = " ")

    >> 5 4 3 2 1
Share