# Move last node to front in linked list

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)

### 5 Thoughts on “Move last node to front in linked list”

1. Amal Murari on September 30, 2014 at 1:23 pm said:

It will not work when we have one node and needs assumption that it needs more than one node

2. void MoveLastNodeToFront(void)
{
if(t1==NULL)
{
printf(“\n\r List is Empty “);
}
{
printf(“\n\r 1st node is last node “);
}
else
{

}
}

3. Vivek Negi on March 28, 2015 at 7:17 am said:

Mr. Niraj…..

node *newnode=new node;
while (temp != NULL){
temp = temp->next;
}
temp->data = newnode->data;
delete newnode;

5. private static void moveFront(Node head) {
Node ptr=null;
while(ptr1.getNextNode()!=null)
{
ptr=ptr1;
ptr1= ptr1.getNextNode();
}

ptr.setNextNode(null);