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 code ; Create a list of 5 nodes
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void setMiddleHead ( Node * * head ) { if ( * head == NULL ) return ; Node * one_node = ( * head ) ; Node * two_node = ( * head ) ; 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 ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * ptr ) { while ( ptr != NULL ) { cout << ptr -> data << " ▁ " ; ptr = ptr -> next ; } cout << endl ; } int main ( ) { Node * head = NULL ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( & head , i ) ; cout << " ▁ list ▁ before : ▁ " ; printList ( head ) ; setMiddleHead ( & head ) ; cout << " ▁ list ▁ After : ▁ " ; printList ( head ) ; return 0 ; }