एक लिंक की गई सूची को देखते हुए, हमें अंतिम तत्व को सामने ले जाना होगा। आइए एक उदाहरण देखें।
इनपुट
1 -> 2 -> 3 -> 4 -> 5 -> NULL
आउटपुट
5 -> 1 -> 2 -> 3 -> 4 -> NULL
एल्गोरिदम
-
लिंक की गई सूची को इनिशियलाइज़ करें।
- यदि लिंक की गई सूची खाली है या इसमें एकल नोड है तो वापस लौटें।
-
लिंक की गई सूची का अंतिम नोड और दूसरा अंतिम नोड खोजें।
-
अंतिम नोड को नया शीर्ष बनाएं।
-
दूसरे अंतिम नोड का लिंक अपडेट करें।
कार्यान्वयन
C++ में उपरोक्त एल्गोरिथम का कार्यान्वयन निम्नलिखित है
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void moveFirstNodeToEnd(struct Node** head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
struct Node* secondLastNode = *head;
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
secondLastNode = lastNode;
lastNode = lastNode->next;
}
secondLastNode->next = NULL;
lastNode->next = *head;
*head = lastNode;
}
void addNewNode(struct Node** head, int new_data) {
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = *head;
*head = newNode;
}
void printLinkedList(struct Node* node) {
while (node != NULL) {
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main() {
struct Node* head = NULL;
addNewNode(&head, 1);
addNewNode(&head, 2);
addNewNode(&head, 3);
addNewNode(&head, 4);
addNewNode(&head, 5);
addNewNode(&head, 6);
addNewNode(&head, 7);
addNewNode(&head, 8);
addNewNode(&head, 9);
moveFirstNodeToEnd(&head);
printLinkedList(head);
return 0;
} आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न परिणाम प्राप्त होंगे।
1->9->8->7->6->5->4->3->2->NULL