Rearrange a given linked list in | Java code to rearrange linked list in place ; function for rearranging a linked list with high and low value . ; Base case . ; two pointer variable . ; swap function for swapping data . ; swap function for swapping data . ; function to insert a Node in the linked list at the beginning . ; function to display Node of linked list . ; Driver code ; let create a linked list . 9 . 6 . 8 . 3 . 7
class Geeks { static class Node { int data ; Node next ; } static Node rearrange ( Node head ) { if ( head == null ) return null ; Node prev = head , curr = head . next ; while ( curr != null ) { if ( prev . data > curr . data ) { int t = prev . data ; prev . data = curr . data ; curr . data = t ; } if ( curr . next != null && curr . next . data > curr . data ) { int t = curr . next . data ; curr . next . data = curr . data ; curr . data = t ; } prev = curr . next ; if ( curr . next == null ) break ; curr = curr . next . next ; } return head ; } static Node push ( Node head , int k ) { Node tem = new Node ( ) ; tem . data = k ; tem . next = head ; head = tem ; return head ; } static void display ( Node head ) { Node curr = head ; while ( curr != null ) { System . out . printf ( " % d ▁ " , curr . data ) ; curr = curr . next ; } } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 7 ) ; head = push ( head , 3 ) ; head = push ( head , 8 ) ; head = push ( head , 6 ) ; head = push ( head , 9 ) ; head = rearrange ( head ) ; display ( head ) ; } }