Sort list

Updated:

LinkedList와 sorting을 이용하면 된다.

  1. 한번 ListNode를 순회하면서 원소들을 뽑아냈다
  2. 그다음 list의 원소를 정렬한후(Comparator이용)
  3. 새롭게 다시 ListNode에 list의 원소들을 집어넣어서 반환하였다

by Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        ListNode temp = head;
        List<Integer> list = new ArrayList<>();
        while(temp!=null) {
            list.add(temp.val);
            temp = temp.next;
        }
        list.sort((a,b)->{
            if(a<b) return -1;
            else if(a>b) return 1;
            else return 0;
        });
        
        ListNode ans = null;
        ListNode cur = null;
        for(Integer a : list) {
            if(cur==null) {
                cur = new ListNode(a);
                ans = cur;
            }
            else {
                cur.next = new ListNode(a);
                cur= cur.next;
            }
        }
        return ans;
    }
}

Leave a comment