Move last element to front of a given Linked List

Move last element to front of a given Linked List

Problem statement: Given a Singly linked list, move the last element to the front of the linked list.
For example,

-> 1 -> 2 -> 3 -> 4 -> 5 -> NULL
-> 5 -> 1 -> 2 -> 3 -> 4 -> NULL
/*C code to move the last element to front of the Linked List */
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int data;
    struct node *next;
} NODE;
NODE *head = NULL;


NODE *newNode(int key)
{
    NODE *temp = (NODE *)malloc(sizeof(NODE));
    temp->data = key;
    temp->next = NULL;
    return temp;
}


void moveToFront()
{

    if (head == NULL || (head)->next == NULL)
        return;
    NODE *secLast = NULL;
    NODE *last = head;

    while (last->next != NULL)
    {
        secLast = last;
        last = last->next;
    }

    secLast->next = NULL;
    last->next = head;
    head = last;
}


void printList()
{
    NODE *temp = head;
    if (temp == NULL)
    {
        printf("List is empty!\n");
        return;
    }
    printf("Linked List is\t");
    while (temp != NULL)
    {
        printf("%d--> ", temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
}


int main()
{
    head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = NULL;
    printList();
    moveToFront();
    printf("Linked list after moving last element to front\n");
    printList();
    return 0;
}

$ ./a.out
Linked List is 1–> 2–> 3–> 4–> 5–> NULL
Linked list after moving last element to front
Linked List is 5–> 1–> 2–> 3–> 4–> NULL
$

If you like the post, please share your feedback!


also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleCircular Linked List
Next articleDoubly Linked List

LEAVE A REPLY

Please enter your comment!
Please enter your name here