Move Last Element to first of LL
Implementation in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node** ref, int newData)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = newData;
newNode->next = (*ref);
(*ref) = newNode;
}
void print(struct node* n)
{
struct node* temp = n;
if(temp == NULL)
{
printf("Empty LinkedList");
}
while(temp!=NULL)
{
printf(" %d",temp->data);
temp=temp->next;
}
}
void relocate(struct node** head)
{
struct node* current= *head;
struct node* temp= NULL;
if(*head == NULL || (*head)->next == NULL)
return;
while(current->next != NULL)
{
temp = current;
current = current->next;
}
temp->next = NULL;
current->next = *head;
*head = current;
}
int main()
{
struct node* head = NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
push(&head,5);
push(&head,6);
push(&head,7);
push(&head,8);
print(head);
relocate(&head);
printf("\n");
print(head);
}
Output:
8 7 6 5 4 3 2 1
1 8 7 6 5 4 3 2
Time Complexity:
O(n)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node** ref, int newData)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = newData;
newNode->next = (*ref);
(*ref) = newNode;
}
void print(struct node* n)
{
struct node* temp = n;
if(temp == NULL)
{
printf("Empty LinkedList");
}
while(temp!=NULL)
{
printf(" %d",temp->data);
temp=temp->next;
}
}
void relocate(struct node** head)
{
struct node* current= *head;
struct node* temp= NULL;
if(*head == NULL || (*head)->next == NULL)
return;
while(current->next != NULL)
{
temp = current;
current = current->next;
}
temp->next = NULL;
current->next = *head;
*head = current;
}
int main()
{
struct node* head = NULL;
push(&head,1);
push(&head,2);
push(&head,3);
push(&head,4);
push(&head,5);
push(&head,6);
push(&head,7);
push(&head,8);
print(head);
relocate(&head);
printf("\n");
print(head);
}
Output:
8 7 6 5 4 3 2 1
1 8 7 6 5 4 3 2
Time Complexity:
O(n)
Comments
Post a Comment