text: Make middle node head in a linked list | C program to make middle node as head of linked list . ; Link list node ; Function to get the middle and set at beginning of the linked list ; To traverse list nodes one by one ; To traverse list nodes by skipping one . ; To keep track of previous of middle ; for previous node of middle node ; move one node each time ; move two node each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; A function to print a given linked list ; Driver function ; Create a list of 5 nodes
code: #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; void setMiddleHead ( struct Node * * head ) { if ( * head == NULL ) return ; struct Node * one_node = ( * head ) ; struct Node * two_node = ( * head ) ; struct Node * prev = NULL ; while ( two_node != NULL && two_node -> next != NULL ) { prev = one_node ; two_node = two_node -> next -> next ; one_node = one_node -> next ; } prev -> next = prev -> next -> next ; one_node -> next = ( * head ) ; ( * head ) = one_node ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * ptr ) { while ( ptr != NULL ) { printf ( " % d ▁ " , ptr -> data ) ; ptr = ptr -> next ; } printf ( " STRNEWLINE " ) ; } int main ( ) { struct Node * head = NULL ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( & head , i ) ; printf ( " ▁ list ▁ before : ▁ " ) ; printList ( head ) ; setMiddleHead ( & head ) ; printf ( " ▁ list ▁ After : ▁ " ) ; printList ( head ) ; return 0 ; }