สมมติว่าเรามีรายการหมายเลขที่เชื่อมโยง เราต้องลบหมายเลขที่ปรากฏหลายครั้งในรายการที่เชื่อมโยง (ถือเพียงหนึ่งรายการในผลลัพธ์) เรายังต้องรักษาลำดับของลักษณะที่ปรากฏในรายการเชื่อมโยงดั้งเดิม
ดังนั้น หากอินพุตเป็นแบบ [2 -> 4 -> 6 -> 1 -> 4 -> 6 -> 9] เอาต์พุตจะเป็น [2 -> 4 -> 6 -> 1 -> 9]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
- ถ้าโหนดไม่เป็นโมฆะ
- l :=ชุดใหม่
- อุณหภูมิ :=โหนด
- ใส่ค่าของ temp ลงใน l
- ในขณะที่ temp ถัดไปไม่เป็นค่าว่าง ให้ทำ
- ถ้าค่าของอุณหภูมิถัดไปไม่อยู่ใน l แล้ว
- ใส่ค่าของอุณหภูมิถัดไปลงใน l
- อุณหภูมิ :=ถัดไปของอุณหภูมิ
- มิฉะนั้น
- ถัดไปของอุณหภูมิ :=ถัดไปของอุณหภูมิถัดไป
- ถ้าค่าของอุณหภูมิถัดไปไม่อยู่ใน l แล้ว
- โหนดส่งคืน
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
ตัวอย่าง
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):
if node:
l = set()
temp = node
l.add(temp.val)
while temp.next:
if temp.next.val not in l: l.add(temp.next.val)
temp = temp.next
else:
temp.next = temp.next.next
return node
ob = Solution()
head = make_list([2, 4, 6, 1, 4, 6, 9])
print_list(ob.solve(head)) อินพุต
[2, 4, 6, 1, 4, 6, 9]
ผลลัพธ์
[2, 4, 6, 1, 9, ]