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

Kiểm tra danh sách liên kết tăng chặt trong Python

Cho đầu danh sách liên kết đơn, kiểm tra giá trị các nút có tăng chặt (strictly ascending) không.

Ví dụ: [2,61,105,157] → True.

Các bước giải quyết (đệ quy)

  • Nếu head.next is None → True
  • Nếu head.val >= head.next.val → False
  • Gọi đệ quy solve(head.next)

Ví dụ mã Python

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, head):
        if head.next is None:
            return True
        if head.val >= head.next.val:
            return False
        return self.solve(head.next)

ob = Solution()
head = make_list([2,61,105,157])
print(ob.solve(head))

Đầu vào

[2,61,105,157]

Đầu ra

True