मान लीजिए हमारे पास कुछ तत्वों के साथ एक लिंक्ड लिस्ट है। हमारा कार्य एक फंक्शन लिखना है जो दिए गए नोड को लिस्ट से हटा देगा। यदि लिस्ट 1 → 3 → 5 → 7 → 9 जैसी है, और 3 को हटाने के बाद, यह 1 → 5 → 7 → 9 हो जाएगी।
मान लीजिए हमारे पास 'node' पॉइंटर है जो हटाए जाने वाले नोड को इंगित करता है, हमें नोड को हटाने के लिए ये ऑपरेशन करने होंगे:
- node.val = node.next.val
- node.next = node.next.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 deleteNode(self, node, data):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
while node.val is not data:
node = node.next
node.val = node.next.val
node.next = node.next.next
head = make_list([1,3,5,7,9])
ob1 = Solution()
ob1.deleteNode(head, 3)
print_list(head)
इनपुट
linked_list = [1,3,5,7,9] data = 3
आउटपुट
[1, 5, 7, 9, ]