Chèn một node vào đầu danh sách liên kết
Ở bài trước, bạn đã học cách hiện thực các lớp Node() và LinkedList().
Trong bài này, bạn sẽ chuẩn bị mã cho phương thức insert_at_beginning() để thêm một node mới vào đầu danh sách liên kết.
Nhắc lại lớp Node():
class Node:
def __init__(self, data):
self.data = data
self.next = None
Bài tập này là một phần của khóa học
Cấu trúc dữ liệu và Thuật toán với Python
Hướng dẫn bài tập
- Tạo node mới.
- Kiểm tra xem danh sách liên kết có node
headhay không. - Nếu danh sách liên kết có node
head, hãy trỏ nodenextcủa node mới đếnhead.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
def insert_at_beginning(self, data):
# Create the new node
new_node = ____(data)
# Check whether the linked list has a head node
if self.____:
# Point the next node of the new node to the head
new_node.___ = self.____
self.head = new_node
else:
self.tail = new_node
self.head = new_node