ভূমিকা
সিঙ্গলি লিংকড লিস্ট (Singly Linked List) থেকে শেষ থেকে n-তম নোড বের করা একটি সাধারণ ইন্টারভিউ প্রশ্ন। দুই পাস পদ্ধতিতে প্রথমে লিস্টের লেংথ বের করা হয়, তারপর (length - n) ধাপ ফরওয়ার্ড যাওয়া হয়।
উদাহরণ কোড
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList_structure:
def __init__(self):
self.head = None
self.last_node = None
def add_vals(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def list_length(my_list):
my_len = 0
curr = my_list.head
while curr:
curr = curr.next
my_len += 1
return my_len
def return_from_end(my_list, n):
l = list_length(my_list)
curr = my_list.head
for i in range(l - n):
curr = curr.next
return curr.data
my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list..').split()
for elem in my_list:
my_instance.add_vals(int(elem))
n = int(input('Enter the value for n.. '))
my_result = return_from_end(my_instance, n)
print('The nth element from the end is: {}'.format(my_result))
আউটপুট
Enter the elements of the linked list.. 45 31 20 87 4 Enter the value for n.. 2 The nth element from the end is: 87
ব্যাখ্যা
Nodeক্লাস:dataএবংnextপয়েন্টার।LinkedList_structure:headএবংlast_nodeট্র্যাক করে O(1) অ্যাপেন্ডে।list_length: লিস্ট ট্রাভার্স করে লেংথ গণনা করে।return_from_end: লেংথlবের করে, হেড থেকেl-nধাপ এগিয়ে টার্গেট নোডে পৌঁছায়।উদাহরণে লিস্ট: 45→31→20→87→4 (লেংথ ৫)। ২য় শেষ = ইনডেক্স ৩ (০-বেসড) = 87।
O(1) স্পেস সমাধান (Two Pointers)
def nth_from_end(head, n):
fast = slow = head
for _ in range(n):
if not fast: return None
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
return slow.data if slow else None
fast পয়েন্টার n ধাপ आगे চলে, তারপর দুটো একসাথে চললে slow শেষ থেকে n-তম এ পৌঁছায়। এক পাস, O(1) স্পেস।