ภาพรวม
เมื่อต้องการหาความยาวของ Linked List โดยไม่ใช้ Recursion จะนิยามเมธอดเพิ่มองค์ประกอบ และเมธอดคำนวณความยาว
ตัวอย่างโค้ด
class Node:
def __init__(self, data):
self.data = data
self.next = None
class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None
def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next
def calculate_length(self):
curr = self.head
length_val = 0
while curr:
length_val = length_val + 1
curr = curr.next
return length_val
my_instance = my_linked_list()
my_data = input('Enter elements of the linked list ').split()
for elem in my_data:
my_instance.add_value(int(elem))
print('The length of the linked list is ' + str(my_instance.calculate_length()))
ผลลัพธ์ตัวอย่าง
Enter elements of the linked list 34 12 56 86 32 99 0 6 The length of the linked list is 8
คำอธิบาย
- สร้างคลาส
Node - สร้างคลาส
my_linked_listพร้อมแอตทริบิวต์ที่จำเป็น - เมธอด
__init__เริ่มต้นโหนดแรก (head) และโหนดสุดท้ายเป็นNone - เมธอด
add_valueเพิ่มข้อมูลเข้า Linked List - เมธอด
calculate_lengthหาความยาวของ Linked List - สร้างอ็อบเจกต์ของ
my_linked_list - รับ input จากผู้ใช้สำหรับองค์ประกอบใน Linked List
- เรียกเมธอดเพื่อเพิ่มข้อมูล
- เรียกเมธอด
calculate_lengthหาความยาว - แสดงผลลัพธ์บนคอนโซล