Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมกลับลำดับลิงก์ลิสต์ใน Python

สมมติว่าเรามีลิงก์ลิสต์ เราต้องกลับลำดับมัน เช่น ถ้ารายการคือ 2 → 4 → 6 → 8 รายการที่กลับแล้วจะเป็น 8 → 6 → 4 → 2

ขั้นตอนการแก้ปัญหา (แบบเรียกซ้ำ)

  1. กำหนดกระบวนการ solve(head, back) สำหรับการกลับลำดับแบบเรียกซ้ำ
  2. ถ้า head ไม่มี ให้คืนค่า head
  3. temp = head.next
  4. head.next = back
  5. back = head
  6. ถ้า temp ว่าง ให้คืนค่า head
  7. head = temp
  8. คืนค่า solve(head, back)

ตัวอย่างโค้ด 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

def print_list(head):
    ptr = head
    print('[', end='')
    while ptr:
        print(ptr.val, end=', ')
        ptr = ptr.next
    print(']')

class Solution(object):
    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, ]

อินพุต / เอาต์พุต

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

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