লিংকড লিস্টের শেষ থেকে k সংখ্যক নোড রিকার্সিভ (recursive) পদ্ধতিতে প্রিন্ট করতে হবে।
রিকার্সিভ পদ্ধতিতে ফাংশন নিজে নিজে কল করে যতক্ষণ না বেস কেস পাওয়া যায়।
উদাহরণ
Linked List: 29->34->43->56->88 Input: k = 2 Output: 88 56

অ্যাপ্রোচ: রিকার্সিভ ফাংশন লিস্টের শেষ থেকে ট্রাভার্স করবে এবং একটি কাউন্টার ভেরিয়েবল দিয়ে ট্র্যাক রাখবে কতবার ট্রাভার্স করা হয়েছে। কাউন্টার k-র চেয়ে ছোট বা সমান হলে নোডের ডেটা প্রিন্ট করবে।
অ্যালগরিদম
START
Step 1: Create node structure
Step 2: Function get(int data) to create new node
Step 3: Function lastval(node* head, int& count, int k)
IF !head RETURN
lastval(head->next, count, k)
count++
IF (count <= k) PRINT head->data
Step 4: In main()
Create list, set k and count=0, call lastval(head, count, k)
STOP
সি প্রোগ্রাম
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* get(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void lastval(struct node* head, int& count, int k) {
if (!head) return;
lastval(head->next, count, k);
count++;
if (count <= k)
printf("%d ", head->data);
}
int main() {
struct node* head = get(11);
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);
lastval(head, count, k);
return 0;
}
আউটপুট
last 2 nodes of a list are: 522 421