Move first element to end of a given Linked List in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that moves the first element to the end of the given linked list.

Let's see the steps to solve the problem.

  • Initialise the linked list.

  • Find the last node of the linked list.

  • Make the second node as the new head.

  • Update the links of first and last nodes.

Example

Let's see the code.

 Live Demo

#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* firstNode = *head;
   struct Node* lastNode = *head;
   while (lastNode->next != NULL) {
      lastNode = lastNode->next;
   }
   *head = firstNode->next;
   firstNode->next = NULL;
   lastNode->next = firstNode;
}
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;
}

Output

If you run the above code, then you will get the following result.

8->7->6->5->4->3->2->1->9->NULL

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Jul-2021 06:46:34
Advertisements