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

Chương trình đảo ngược danh sách liên kết bằng Python


Cho một danh sách liên kết, yêu cầu đảo ngược nó. Ví dụ: 2 → 4 → 6 → 8 trở thành 8 → 6 → 4 → 2.

Quy trình giải quyết (Đệ quy)

  1. Định nghĩa hàm solve(head, back).
  2. Nếu head là None, trả về head.
  3. Lưu temp = head.next.
  4. Gán head.next = back, cập nhật back = head.
  5. Nếu temp là None, trả về head.
  6. Gán head = temp và gọi đệ quy solve(head, back).

Ví dụ mã nguồn

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 print_list(head):
    ptr = head
    print('[', end="")
    while ptr:
        print(ptr.val, end=", ")
        ptr = ptr.next
    print(']')

class Solution:
    def reverseList(self, head):
        return self.solve(head, None)

    def solve(self, head, back):
        if not head:
            return head
        temp = head.next
        head.next = back
        back = head
        if not temp:
            return head
        head = temp
        return self.solve(head, back)

list1 = make_list([5,8,9,6,4,7,8,1])
ob1 = Solution()
list2 = ob1.reverseList(list1)
print_list(list2)
# Output: [1, 8, 7, 4, 6, 9, 8, 5, ]

Đầu vào

[5,8,9,6,4,7,8,1]

Đầu ra

[1, 8, 7, 4, 6, 9, 8, 5, ]