Move Last Element to Front of a Linked List
You are given the head of a Linked List. You have to move the last element to the front of the Linked List and return the list.
Example 1:
Input: N = 5 List = {2,5,6,2,1} Output: {1,2,5,6,2} Explanation: In the given linked list, the last element is 1, after moving the last element to the front the linked list will be {1,2,5,6,2}.
//{ Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int x){
val=x;
next=NULL;
}
};
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
ListNode *moveToFront(ListNode *head){
if(head==NULL) return NULL;
else if(head->next ==NULL) return head;
else if(head->next->next ==NULL){
ListNode *temp =head, *t=head;
head = head ->next;
t->next= NULL;
head->next= temp;
}
else {
ListNode *temp = head, *t =head->next, *t1=head;
while(temp->next!=NULL){
temp = temp->next;
}
while(t->next->next!=NULL){
t = t->next;
}
t->next =NULL;
head = temp;
head->next = t1;
return head;
}
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<ListNode*> a(n);
for(int i=0;i<n;i++){
int x;
cin>>x;
a[i]=new ListNode(x);
if(i!=0){
a[i-1]->next=a[i];
}
}
ListNode *head=a[0];
Solution ob;
head=ob.moveToFront(head);
while(head!=NULL){
cout<<head->val;
if(head->next!=NULL){
cout<<" ";
}
head=head->next;
}
cout<<endl;
}
return 0;
}
// } Driver Code Ends
Happy Coding 😊.