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