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

ความยาวของ Linked List ใน Python

สมมติว่าเรามี singly linked list เราต้องหาความยาวของมัน Linked list มีฟิลด์ next และ val

ตัวอย่าง

หากอินพุตคือ [2 → 4 → 5 → 7 → 8 → 9 → 3] ผลลัพธ์จะเป็น 7

ขั้นตอนการแก้ปัญหา

  1. count := 0
  2. ในขณะที่ node ไม่ใช่ null:
    • count := count + 1
    • node := next ของ node
  3. คืนค่า count

การใช้งาน

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

def make_list(elements):
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

class Solution:
    def solve(self, node):
        count = 0
        while node:
            count += 1
            node = node.next
        return count

ob = Solution()
head = make_list([2,4,5,7,8,9,3])
print(ob.solve(head))

อินพุต

[2,4,5,7,8,9,3]

เอาต์พุต

7