Problem Statement:
Write a function that moves last element to front in a given singly Linked List.
For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4.
You just need to return the head of new linked list, don’t print the elements.
Input format :
Line 1 : Linked list elements of length n (separated by space and terminated by -1)
Output format :
Updated list elements (separated by space)
Constraints :
1 <= n <= 10^4
Sample Input :
1 2 3 4 5 6 -1
Note : -1 at the end of input is just a terminator representing the end of linked list. This -1 is not part of the linked list. Size of given linked list is 6.
Sample Output :
6 1 2 3 4 5
/*************
Following is the Node structure already written.
template
class Node {
public:
T data;
Node* next;
Node(T data) {
next = NULL;
this->data = data;
}
~Node() {
if (next != NULL) {
delete next;
}
}
};
*************/
Node* moveToFront(Node *head_ref) {
if(head_ref->data==-1 || head_ref->next->data==-1){
return head_ref;
}
Node temp=head_ref;
Node x1;
while(temp->next->data!=-1){
temp=x1;
temp=temp->next;
}
x1->next=NULL;
delete temp;
int x=temp->data;
Node *t1;
t1->data=x;
t1->next=head_ref;
t1=head_ref;
}
Run time error is coming