Python 中链表的长度

pythonserver side programmingprogramming更新于 2025/12/27 8:12:17

假设我们有一个单链表,我们必须找到它的长度。链表有字段 next 和 val。

因此,如果输入为 [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3],则输出为 7。

为了解决这个问题,我们将遵循以下步骤 −

  • count := 0
  • 当节点非空时,执行
    • count := count + 1
    • node:= next of node
  • 返回 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

相关文章


有用资源