Cách triển khai Linked List bằng Stack là gì?
Cách triển khai Linked List bằng Stack là gì?
Cài đặt Stack bằng Linked List: push/pop thao tác ở đầu danh sách (head) ⇒ O(1), không cần cấp phát lại.
class Node:
def __init__(self, val, nxt=None): self.val, self.next = val, nxt
class Stack:
def __init__(self): self.head, self.size = None, 0
def push(self, x): self.head = Node(x, self.head); self.size += 1
def pop(self):
if not self.head: raise IndexError("stack rỗng")
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.