Write a C 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.
1) Traverse the linked list till last node.
2) Use two pointers – one points to last node and other to second last node.
3) After the end of loop do following operations.
i) Make second last as last, set next of it to NULL.
ii) Set next of last as root.
iii) Make last as root node.
void moveLastToFront(node **root) { node* prev = NULL; node* last = *root; while( last->next != NULL) { prev = ptr; last = last->next; } prev->next = NULL; last->next = *root; *root = last; }
Time Complexity O(N)
It will not work when we have one node and needs assumption that it needs more than one node
void MoveLastNodeToFront(void)
{
struct SingleLinkList *t1,*temp;
t1=head;
if(t1==NULL)
{
printf(“\n\r List is Empty “);
}
else if(t1->link == NULL)
{
printf(“\n\r 1st node is last node “);
}
else
{
while(t1->link->link)
t1=t1->link;
temp=t1->link;
t1->link=NULL;
temp->link=head;
head=temp;
}
}
Mr. Niraj…..
your program is correct
node *temp = head;
node *newnode=new node;
while (temp != NULL){
temp = temp->next;
}
newnode->data = head->data;
head->data = temp->data;
temp->data = newnode->data;
delete newnode;
private static void moveFront(Node head) {
Node ptr1 = head;
Node ptr=null;
while(ptr1.getNextNode()!=null)
{
ptr=ptr1;
ptr1= ptr1.getNextNode();
}
ptr.setNextNode(null);
ptr1.setNextNode(head);
head = ptr1;
}