Here we are going to write a program to make middle node head in linked list. Suppose we are having n number of nodes in the linked list, if n is odd then n/2 is the middle node so in that case we will change the head and make the (n/2)th node head and if n is even then n/2 + 1 will be the middle node so in that case we will set the (n/2 + 1)th node head.
Suppose,
Input- 1 => 2 => 3 => 4 => 5 => NULL
Output- 3 => 1 => 2 => 4 => 5 => NULL
So now lets implement it
Program to make middle node head in Linked List-
C Code-
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
void create(struct node** head,int val){
struct node* temp=*head;
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(*head==NULL){
*head=newnode;
return;
}
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newnode;
}
int length(struct node* head){
struct node* temp=head;
int c=0;
while(temp->next!=NULL){
temp=temp->next;
c=c+1;
}
return c/2;
}
void makemiddlehead(struct node** head,int pos){
struct node* temp=*head;
struct node* t;
int c=1;
while(c!=pos){
temp=temp->next;
c=c+1;
}
t=temp->next;
temp->next=temp->next->next;
t->next=*head;
*head=t;
// return head;
}
void display(struct node* head){
while(head!=NULL){
printf("%d => ",head->data);
head=head->next;
}
printf("NULL\n");
}
int main(){
struct node* head=NULL;
create(&head,1);
create(&head,2);
create(&head,3);
create(&head,4);
create(&head,5);
create(&head,6);
create(&head,7);
display(head);
int l=length(head);
makemiddlehead(&head,l);
display(head);
return 0;
}
Output-
1 => 2 => 3 => 4 => 5 => 6 => 7 => NULL
4 => 1 => 2 => 3 => 5 => 6 => 7 => NULL Time Complexity: O(n) where n is the length of the linked list.
Linked List Problems-
Post a Comment
If you have any doubts, please let me know