समस्या विवरण
लिंक्ड लिस्ट को रिवर्स क्रम में प्रिंट करें बिना लिस्ट को संशोधित किए और केवल एक बार ट्रैवर्स करके।
रोचक दृष्टिकोण: कैरिज रिटर्न (\r) का उपयोग
कैरिज रिटर्न कर्सर को लाइन की शुरुआत में ले जाता है। तर्क:
- पहले तत्व से पहले n-1 स्पेस छोड़ें
- दूसरे से पहले n-2 स्पेस छोड़ें
- इस तरह प्रत्येक तत्व सही स्थिति पर प्रिंट होकर रिवर्स क्रम बनाता है
उदाहरण कोड
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void printReverse(struct Node** head_ref, int n) {
int j = 0;
struct Node* current = *head_ref;
while (current != NULL) {
for (int i = 0; i < 2 * (n - j); i++)
cout << " ";
cout << current->data << "\r";
current = current->next;
j++;
}
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int printList(struct Node* head) {
int i = 0;
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
i++;
}
return i;
}
int main() {
struct Node* head = NULL;
push(&head, 2);
push(&head, 7);
push(&head, 3);
push(&head, 5);
push(&head, 4);
push(&head, 6);
printf("Given linked list:\n");
int n = printList(head);
printf("\nReversed Linked list:\n");
printReverse(&head, n);
return 0;
}
आउटपुट
Given linked list: 6 4 5 3 7 2 Reversed Linked list: 2 7 3 5 4 6