কাজটি হল পুনরাবৃত্ত পদ্ধতি ব্যবহার করে লিঙ্ক করা তালিকার শেষ থেকে শুরু করে k নোডগুলি প্রিন্ট করা৷
রিকার্সিভ অ্যাপ্রোচ হল এমন একটি যেখানে ফাংশনটি কল করা না হওয়া পর্যন্ত বার বার কল করে এবং ফল সঞ্চয় করে।
ধরা যাক, তালিকায় 29, 34, 43, 56 এবং 88 নোড রয়েছে এবং k-এর মান 2 আউটপুট থেকে শেষ k নোড যেমন 56 এবং 88 হবে।

উদাহরণ
Linked List: 29->34->43->56->88 Input: 2 Output: 88 56
যেমন উল্লেখ করা হয়েছে পুনরাবৃত্ত পদ্ধতি ব্যবহার করা উচিত যা তালিকাটিকে শেষ থেকে কতবার অতিক্রম করতে হবে তার ট্র্যাক রাখবে এবং একটি পয়েন্টার ভেরিয়েবল দ্বারা kth মান পর্যন্ত রিকার্সিভ ফাংশনকে কল করা হবে।
নিচের কোডটি প্রদত্ত অ্যালগরিদমের সি বাস্তবায়ন দেখায়।
অ্যালগরিদম
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> Declare function as node* get(int data) Create newnode using malloc function Set newnode->data = data Set newnode->next = NULL return newnode step 3 -> Declare function void lastval(node* head, int& count, int k) IF !head Return Set lastval(head->next, count, k) Set count++ IF (count <= k) Print head->data Step 4 -> In Main() Generate head using node* head = get(11) Set k and count to 0 Call lastval(head,k,count) STOP
উদাহরণ
#include<stdio.h>
#include<stdlib.h>
// Structure of a node
struct node {
int data;
node* next;
};
// Function to get a new node
node* get(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
//print the last k values of a node
void lastval(node* head, int& count, int k) {
if (!head)
return;
lastval(head->next, count, k);
count++;
if (count <= k)
printf("%d ", head->data);
}
int main() {
node* head = get(11); //inserting elements into the list
head->next = get(243);
head->next->next = get(321);
head->next->next->next = get(421);
head->next->next->next->next = get(522);
int k = 2, count = 0;
printf(" last %d nodes of a list are :",k);
// print last k nodes
lastval(head, count, k);
return 0;
} আউটপুট
যদি আমরা উপরের প্রোগ্রামটি চালাই তবে এটি নিম্নলিখিত আউটপুট তৈরি করবে।
last 2 nodes of a list are :522 421