Search code examples
javalinked-list

Move the Smallest and largest to head and tail of linked list


How to return a Linked list with head as minimum element and tail as maximum?

The function shiftSmallLarge() takes the head node of a linked list as a parameter and returns the head pointer after doing both shifts.

static Node shiftSmallLarge(Node head){
 if(head==null){
  return null;
}
  Node temp=head;
  Node min=head;
  Node max=head;
  while(temp.next!=null){
  
    if(temp.data<min.data){
      min=temp;
    }
    if(temp.data>max.data){
      max=temp;
    }
    temp=temp.next;
  }
  
}

Solution

  • You can get previous node in linked list by making two pointers initialize one pointer from null and other from head of list. Iterate other node which you initialize from head till the node which you want and iterate the first node before the 2nd node.