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