Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python หาจำนวนครั้งที่เกิดของทุกองค์ประกอบใน Linked List


ภาพรวม

เมื่อต้องการหาจำนวนครั้งที่เกิดของทุกองค์ประกอบใน Linked List จะนิยามเมธอดสำหรับเพิ่มองค์ประกอบ แสดงองค์ประกอบ และนับจำนวนครั้งที่เกิดขององค์ประกอบทั้งหมด

ตัวอย่างโค้ด

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList_structure:
    def __init__(self):
        self.head = None
        self.last_node = None

    def add_vals(self, data):
        if self.last_node is None:
            self.head = Node(data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(data)
            self.last_node = self.last_node.next

    def print_it(self):
        curr = self.head
        while curr:
            print(curr.data)
            curr = curr.next

    def count_elem(self, key):
        curr = self.head
        count_val = 0
        while curr:
            if curr.data == key:
                count_val = count_val + 1
            curr = curr.next
        return count_val

my_instance = LinkedList_structure()
my_list = [56, 78, 98, 12, 34, 55, 0]
for elem in my_list:
    my_instance.add_vals(elem)
print('The linked list is : ')
my_instance.print_it()
key_val = int(input('Enter the data item '))
count_val = my_instance.count_elem(key_val)
print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val))

ผลลัพธ์ตัวอย่าง

The linked list is : 56 78 98 12 34 55 0
Enter the data item 0
0 occurs 1 time(s) in the list.

คำอธิบาย

  • สร้างคลาส Node
  • สร้างคลาส LinkedList_structure พร้อมแอตทริบิวต์ที่จำเป็น
  • เมธอด __init__ เริ่มต้นโหนดแรก (head) เป็น None
  • เมธอด add_vals เพิ่มค่าเข้า Linked List
  • เมธอด print_it แสดงค่าของ Linked List บนคอนโซล
  • เมธอด count_elem หาจำนวนครั้งที่เกิดขององค์ประกอบที่ระบุใน Linked List
  • สร้างอินสแตนซ์ของ LinkedList_structure
  • นิยามรายการองค์ประกอบ
  • วนลูปเพิ่มองค์ประกอบเข้า Linked List
  • แสดงองค์ประกอบบนคอนโซล
  • เรียกเมธอด count_elem กับ Linked List นี้
  • แสดงผลลัพธ์บนคอนโซล