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

โปรแกรมจัดเรียงลิงค์ด์ลิสต์โดยสลับโหนดหน้า-หลังใน Python

สมมติว่าเรามี singly linked list ต้องจัดเรียงใหม่โดยเอา: โหนดสุดท้าย, แล้วโหนดแรก, แล้วโหนดสุดท้ายลำดับที่สอง, แล้วโหนดลำดับที่สอง, ... สลับกันไปเรื่อยๆ

ตัวอย่าง

อินพุต: [1,2,3,4,5,6,7,8,9]

เอาต์พุต: [9, 1, 8, 2, 7, 3, 6, 4, 5]

ขั้นตอนการแก้ปัญหา

  1. เดินผ่าน linked list เก็บค่าทุกโหนดใส่ลิสต์ l
  2. เดินผ่าน linked list อีกครั้ง เปลี่ยนค่าโหนดโดยสลับดึงจากท้ายและหัวของ l:
    • ดึงค่าจากท้าย (l.pop()) ใส่โหนดปัจจุบัน
    • ไปโหนดถัดไป ถ้าจบ break
    • ดึงค่าจากหัว (l.pop(0)) ใส่โหนดปัจจุบัน
    • ไปโหนดถัดไป
  3. คืนค่า head ของ linked list

การนำไปใช้ใน 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:
    def solve(self, node):
        c = node
        l = []
        while c:
            l.append(c.val)
            c = c.next
        c = node
        while c and l:
            c.val = l.pop()
            c = c.next
            if c is None:
                break
            c.val = l.pop(0)
            c = c.next
        return node

ob = Solution()
head = make_list([1,2,3,4,5,6,7,8,9])
print_list(ob.solve(head))

อินพุต

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

เอาต์พุต

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