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 |
Here we traverse the linked list till the next pointer is NULL, store the last and second last element in two variables.
 Â
NODE *secLast = NULL;
Â
NODE *last = head;
  while
(last->next != NULL)
   Â
{
       Â
secLast = last;
       Â
last = last->next;
   Â
}
When we reach NULL pointer, assign the second last element’s next to NULL pointer.
   Â
secLast->next = NULL;
Assign last element’s next to head.
   Â
last->next = head;
At last assign the head to last element.
  Â
 head = last;
[code language=”cpp”]
/*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;
}
[/code]
$ ./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 $ |
also read:
HTML | DATA STRUCTURE |
DBMS | REASONING |
C PROGRAM | APTITUDE |
E-LEARNING |