Java how to sort a Linked List?

后端 未结 9 1925
耶瑟儿~
耶瑟儿~ 2020-12-03 03:00

I am needing to sort a linked list alphabetically. I have a Linked List full of passengers names and need the passengers name to be sorted alphabetically. How would one do t

相关标签:
9条回答
  • 2020-12-03 03:44

    Elegant solution since JAVA 8:

    LinkedList<String>list = new LinkedList<String>();
    list.add("abc");
    list.add("Bcd");
    list.add("aAb");
    
    list.sort(String::compareToIgnoreCase);
    

    Another option would be using lambda expressions:

    list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));
    
    0 讨论(0)
  • 2020-12-03 03:44
    Node mergeSort(Node head) {
        if(head == null || head.next == null) {
            return head;
        }
    
        Node middle = middleElement(head);
        Node nextofMiddle = middle.next;
        middle.next = null;
    
        Node left = mergeSort(head);
        Node right = mergeSort(nextofMiddle);
    
        Node sortdList = merge(left, right);
    
        return sortdList;
    }
    
    Node merge(Node left, Node right) {
        if(left == null) {
            return right;
        }
    
        if(right == null) {
            return left;
        }
        Node temp = null;
        if(left.data < right.data) {
            temp = left;
            temp.next = merge(left.next, right);
        } else {
            temp = right;
            temp.next = merge(left, right.next);
        }
    
        return temp;
    }
    
    Node middleElement(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
    
    0 讨论(0)
  • 2020-12-03 03:49

    In order to sort Strings alphabetically you will need to use a Collator, like:

     LinkedList<String> list = new LinkedList<String>();
     list.add("abc");
     list.add("Bcd");
     list.add("aAb");
     Collections.sort(list, new Comparator<String>() {
         @Override
         public int compare(String o1, String o2) {
             return Collator.getInstance().compare(o1, o2);
         }
     });
    

    Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

    For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

    Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

    0 讨论(0)
提交回复
热议问题