मान लीजिए हमारे पास एक लिंक्ड लिस्ट है। हमें लिस्ट के अंत से Nth नोड को हटाना है, फिर उसका हेड लौटाना है। इसलिए यदि लिस्ट [1, 2, 3, 4, 5, 6] की तरह है और n = 3, तो वापस की गई लिस्ट [1, 2, 3, 5, 6] होगी।
इसे हल करने के लिए, हम इन चरणों का पालन करेंगे −
- यदि हेड के बाद कोई नोड नहीं है, तो None लौटाएं
- front := head, back := head, counter := 0 और flag := false
- जब तक counter <= n
- यदि front मौजूद नहीं है, तो flag को true सेट करें, और लूप से बाहर आएं
- front := front का नेक्स्ट, और counter को 1 से बढ़ाएं
- जब तक front मौजूद है
- front := front का नेक्स्ट
- back := back का नेक्स्ट
- यदि flag false है, तो
- temp := back का नेक्स्ट
- back का नेक्स्ट := temp का नेक्स्ट
- temp का नेक्स्ट := None
- अन्यथा head := 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(object): def removeNthFromEnd(self, head, n): if not head.next: return None front=head back = head counter = 0 flag = False while counter<=n: if(not front): flag = True break front = front.next counter+=1 while front: front = front.next back = back.next if not flag: temp = back.next back.next = temp.next temp.next = None else: head = head.next return head head = make_list([1,2,3,4,5,6]) ob1 = Solution() print_list(ob1.removeNthFromEnd(head, 3))इनपुट
[1,2,3,4,5,6] 3
आउटपुट
[1,2,3,5,6]