สมมติว่าเรามีรายการที่เชื่อมโยง เราต้องย้อนกลับ ดังนั้นหากรายการเป็นแบบ 2 -> 4 -> 6 -> 8 รายการที่กลับรายการใหม่จะเป็น 8 -> 6 -> 4 -> 2
เพื่อแก้ปัญหานี้ เราจะปฏิบัติตามแนวทางนี้ -
- กำหนดหนึ่งโพรซีเดอร์เพื่อทำการกลับรายการแบบเรียกซ้ำเป็นแก้ (หัว, ย้อนกลับ)
- ถ้าไม่มีหัวให้กลับหัว
- temp :=head.next
- head.next :=ย้อนกลับ
- หลัง :=หัว
- ถ้าว่างก็กลับหัว
- หัว :=อุณหภูมิ
- แก้กลับ(หัว,กลับ)
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
ตัวอย่าง
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) อินพุต
[5,8,9,6,4,7,8,1]
ผลลัพธ์
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13,]