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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

<

Given a linked list, we have to move the first element to the end. Let's see an example.

Input

1 -> 2 -> 3 -> 4 -> 5 -> NULL

Output

2 -> 3 -> 4 -> 5 -> 1 -> NULL


## Algorithm

• Initialise the linked list.

• Return if the linked list is empty or it has single node.
• Find the last node of the linked list.

• Make the second node as the new head.

• Update the links of first and last nodes.

## Implementation

Following is the implementation of the above algorithm in 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* firstNode = *head;
struct Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
firstNode->next = NULL;
lastNode->next = firstNode;
}
void addNewNode(struct Node** head, int new_data) {
struct Node* newNode = new Node;
newNode->data = new_data;
}
void printLinkedList(struct Node* node) {
while (node != NULL) {
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main() {
struct Node* head = NULL;
}
8->7->6->5->4->3->2->1->9->NULL