在 Python 中检查给定链表的长度是偶数还是奇数


假设我们有一个链表,我们需要检查它的长度是奇数还是偶数。

因此,如果输入类似 head = [5,8,7,4,3,6,4,5,8],那么输出将是 Odd(奇数)。

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

  • 当 head 不为 null 且 head 的下一个不为 null 时,进行
    • head := head 的下一个的下一个
  • 如果 head 为 null,则
    • 返回 "偶数"
  • 返回 "奇数"

下面我们来看以下实现以获得更好的理解 -

示例代码

在线演示

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
      
def solve(head):
   while head != None and head.next != None: 
      head = head.next.next
           
   if head == None:
      return "Even"
   return "Odd"

head = make_list([5,8,7,4,3,6,4,5,8])
print(solve(head))

输入

[5,8,7,4,3,6,4,5,8]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Odd

更新日期:16-Jan-2021

151 次浏览

开启您的事业

完成此课程并获得认证

立即开始
广告