Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Độ dài danh sách liên kết trong Python


Cho danh sách liên kết đơn, tìm độ dài của nó. Danh sách liên kết có các trường next và val.

Ví dụ, [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3], đầu ra 7.

Các bước giải quyết:

  • count := 0.
  • Trong khi node không null:
    • count += 1.
    • node = node.next.
  • Trả về count.

Ví dụ minh họa

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))

Đầu vào

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

Đầu ra

7