สมมติว่าเรามีรายการเชื่อมโยง เราต้องเรียงลำดับจากน้อยไปมาก
ดังนั้น หากอินพุตเป็น [5, 8, 4, 1, 5, 6, 3] ผลลัพธ์จะเป็น [1, 3, 4, 5, 5, 6, 8, ]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้:
- ค่า :=รายการใหม่
- หัว :=โหนด
- ในขณะที่โหนดไม่เป็นโมฆะให้ทำ
- ใส่ค่าของโหนดที่ส่วนท้ายของค่า
- โหนด :=ถัดไปของโหนด
- จัดเรียงรายการค่า
- values :=สร้างคิวแบบ double-ended โดยรับองค์ประกอบของค่า
- โหนด :=หัว
- ในขณะที่โหนดไม่เป็นโมฆะให้ทำ
- ค่าของโหนด :=องค์ประกอบด้านซ้ายของคิวและลบองค์ประกอบจากด้านซ้ายของคิว
- โหนด :=ถัดไปของโหนด
- กลับหัว
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น:
ตัวอย่าง
import collections
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):
values = []
head = node
while node:
values.append(node.val)
node = node.next
values.sort()
values = collections.deque(values)
node = head
while node:
node.val = values.popleft()
node = node.next
return head
ob = Solution()
head = make_list([5, 8, 4, 1, 5, 6, 3])
print_list(ob.solve(head)) อินพุต
[5, 8, 4, 1, 5, 6, 3]
ผลลัพธ์
[1, 3, 4, 5, 5, 6, 8, ]