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)
    {
    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;
    }
    }

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

    Mr. Niraj…..
    your program is correct

  4. 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;

  5. 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;

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation