हमें लिंक की गई सूची के नोड्स की 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 तत्वों को हटाना है, इसलिए स्टैक डेटा संरचना का उपयोग करने का सबसे अच्छा तरीका है जिसमें तत्वों को धक्का दिया जाता है जो सूची बनाएगा और स्टैक के शुरुआती तत्व सूची के अंतिम तत्व हैं और वे हैं स्टैक से kth संख्या तक हमें लिंक की गई सूची के अंतिम नोड्स देते हुए पॉप आउट करें।
नीचे दिया गया कोड दिए गए एल्गोरिथम के c कार्यान्वयन को दर्शाता है।
एल्गोरिदम
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> create struct node* intoList(int data) Create newnode using malloc Set newnode->data = data newnode->next = NULL return newnode step 3 -> Declare function void rev(struct node* head,int count, int k) create struct node* temp1 = head Loop While(temp1 != NULL) count++ temp1 = temp1->next end Declare int array[count], temp2 = count,i Set temp1 = head Loop While(temp1 != NULL) Set array[--temp2] = temp1->data Set temp1 = temp1->next End Loop For i = 0 and i < k and i++ Print array[i] End Step 4 -> In Main() Create list using struct node* head = intoList(9) Set k=3 and count=0 Call rev(head,count,k) STOP
उदाहरण
#include<stdio.h>
#include<stdlib.h>
// Structure of a node
struct node {
int data;
struct node *next;
};
//functon for inserting a new node
struct node* intoList(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
// Function to reversely printing the elements of a node
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); //inserting elements into a list
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); //calling function to print reversely
return 0;
} आउटपुट
यदि हम उपरोक्त प्रोग्राम चलाते हैं तो यह निम्न आउटपुट उत्पन्न करेगा।
reverse of a list is : 109 55 24