Home > Blockchain >  Sorting an Single Singly Linked list
Sorting an Single Singly Linked list

Time:10-04

Is there any way or method in java Collection framework through which we can sort a singly Linked list directly as we do with lists. ex Collections.sort(lists);

Singly Linked List 5-->4-->3-->2-->1

Sort it is ascending order 1-->2-->3-->4-->5

Please try to answer the question in Java.

CodePudding user response:

If the (hypothetical) singly linked list implements the java.util.List interface, then you can sort it using Collections.sort. Otherwise, it cannot be done using the (standard) Java collections framework.

You could ... of course ... copy the (hypothetical) linked list elements to (say) an ArrayList, sort that using Collections.sort, then copy the elements of the sorted ArrayList back replacing the linked list elements.

CodePudding user response:

The java.util.Collections contains the Collections.sort(); function. Within that the Collections.reverseOrder() can be utilised.

For example:

import java.util.Arrays;  
import java.util.Collections;  //import Collections
import java.util.List;  
public class TestList  
{  
public static void main(String args[])   
    {  
        List<Integer> testList = Arrays.asList(5,4,3,2,1);  
        Collections.sort(testList, Collections.reverseOrder()); //use Collections to reverse the list order
        System.out.println(testList);  
    }  
}  

The resultant console output would be [1, 2, 3, 4, 5]

  • Related