

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Move last element to front of a given Linked List in C++
Given a linked list, we have to move the last element to the front. Let's see an example.
Input
1 -> 2 -> 3 -> 4 -> 5 -> NULL
Output
5 -> 1 -> 2 -> 3 -> 4 -> NULL
Algorithm
Initialise the linked list.
- Return if the linked list is empty or it has single node.
Find the last node and second last nodes of the linked list.
Make the last node as new head.
Update the link of second last node.
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* 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; }
Output
If you run the above code, then you will get the following result.
1->9->8->7->6->5->4->3->2->NULL
- Related Questions & Answers
- Move first element to end of a given Linked List in C++
- Move all zeros to the front of the linked list in C++
- Find the product of last N nodes of the given Linked List in C++
- Program to remove last occurrence of a given target from a linked list in Python
- Shift last given number of elements to front of array JavaScript
- Java Program to Add Element at First and Last Position of a Linked list
- Remove Last Node of the Linked List using C++
- C++ Pairwise Swap Elements of a Given Linked List
- How to Segregate a given Linked List in C++
- Search an element in the given singly Linked List using C++
- Find a peak element in Linked List in C++
- Create new linked list from two given linked list with greater element at each node in C++ Program
- Reverse a Linked List in groups of a Given Size using C++
- Find the last element of a list in scala
- Find the second last node of a linked list in single traversal in C++
Advertisements