हमें लिंक्ड लिस्ट के k नंबर के नोड्स को रिवर्स क्रम में प्रिंट करना है। इस समस्या को हल करने के लिए हमें इटरेटिव दृष्टिकोण लागू करना होगा।
इटरेटिव मेथड वह है जो आमतौर पर लूप का उपयोग करता है जो तब तक निष्पादित होता है जब तक कंडीशन का मान 1 या सत्य रहता है।
मान लें, लिस्ट में नोड्स 29, 34, 43, 56 और 88 हैं और k का मान 2 है तो आउटपुट k तक वैकल्पिक नोड्स होंगे जैसे 56 और 88।

उदाहरण
Linked List: 29->34->43->56->88 Input: 2 Output: 56 88
चूंकि हमें लिस्ट से अंतिम k एलिमेंट्स निकालने हैं, इसका सबसे अच्छा तरीका स्टैक डेटा संरचना का उपयोग करना है जिसमें एलिमेंट्स पुश किए जाएंगे जो लिस्ट बनाएंगे और स्टैक के शुरुआती एलिमेंट्स लिस्ट के अंतिम एलिमेंट्स होंगे और उन्हें स्टैक से kवीं बार तक पॉप आउट किया जाएगा जिससे हमें लिंक्ड लिस्ट के अंतिम नोड्स मिलेंगे।
एल्गोरिदम
शुरुआत
चरण 1 → नोड वेरिएबल को संरचना टाइप का बनाएं
int data घोषित करें
*next का उपयोग करके नोड टाइप का पॉइंटर घोषित करें
चरण 2 → struct node* intoList(int data) बनाएं
malloc का उपयोग करके newnode बनाएं
newnode->data = data सेट करें
newnode->next = NULL
newnode रिटर्न करें
चरण 3 → void rev(struct node* head, int count, int k) फंक्शन घोषित करें
struct node* temp1 = head बनाएं
लूप जब तक (temp1 != NULL)
count++
temp1 = temp1->next
लूप समाप्त
int array[count], temp2 = count, i घोषित करें
temp1 = head सेट करें
लूप जब तक (temp1 != NULL)
array[--temp2] = temp1->data सेट करें
temp1 = temp1->next
लूप समाप्त
i = 0 से k तक i++ लूप
array[i] प्रिंट करें
लूप समाप्त
चरण 4 → main() में
struct node* head = intoList(9) का उपयोग करके लिस्ट बनाएं
k=3 और count=0 सेट करें
rev(head,count,k) कॉल करें
समाप्त
उदाहरण
#include <stdio.h>
#include <stdlib.h>
// नोड की संरचना
struct node {
int data;
struct node *next;
};
// नया नोड डालने का फंक्शन
struct node* intoList(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
// नोड के एलिमेंट्स को रिवर्सली प्रिंट करने का फंक्शन
void rev(struct node* head, int count, int k) {
struct node* temp1 = head;
while(temp1 != NULL) {
count++;
temp1 = temp1->next;
}
int array[count], temp2 = count, i;
temp1 = head;
while(temp1 != NULL) {
array[--temp2] = temp1->data;
temp1 = temp1->next;
}
for(i = 0; i < k; i++)
printf("%d ", array[i]);
}
int main() {
printf("\nreverse of a list is : ");
struct node* head = intoList(9);
head->next = intoList(76);
head->next->next = intoList(13);
head->next->next->next = intoList(24);
head->next->next->next->next = intoList(55);
head->next->next->next->next->next = intoList(109);
int k = 3, count = 0;
rev(head, count, k);
return 0;
}
आउटपुट
यदि हम उपरोक्त प्रोग्राम चलाते हैं तो यह निम्नलिखित आउटपुट उत्पन्न करेगा।
reverse of a list is : 109 55 24