Triển khai cấu trúc ngăn xếp

Ngăn xếp có thể được thực hiện với danh sách tuần tự hoặc danh sách liên kết.

Hoạt động ngăn xếp

  • Stack () tạo một ngăn xếp trống mới

  • push (item) thêm một phần tử mới vào đầu ngăn xếp

  • pop () Bật phần tử trên cùng của ngăn xếp

  • peek () trả về phần tử trên cùng của ngăn xếp

  • is_empty () Xác định xem ngăn xếp có trống không

  • size () trả về số phần tử trong ngăn xếp

class Stack(object):
    def __init__(self):
         self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

if __name__ == "__main__":
    stack = Stack()
    stack.push("hello")
    stack.push("world")
    stack.push("itcast")
    print stack.size()
    print stack.peek()
    print stack.pop()
    print stack.pop()
    print stack.pop()

Quá trình thực hiện như sau: bản trình diễn ngăn xếp

Last updated

Was this helpful?