Make middle node head in a linked list | Java 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
public class GFG { static class Node { int data ; Node next ; Node ( int data ) { this . data = data ; next = null ; } } static Node head ; static void setMiddleHead ( ) { 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 ; } static void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } static void printList ( Node ptr ) { while ( ptr != null ) { System . out . print ( ptr . data + " ▁ " ) ; ptr = ptr . next ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { head = null ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( i ) ; System . out . print ( " ▁ list ▁ before : ▁ " ) ; printList ( head ) ; setMiddleHead ( ) ; System . out . print ( " ▁ list ▁ After : ▁ " ) ; printList ( head ) ; } }