题目
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
法一:暴力
我将链表结点的值都取出来放在list里面,然后对list进行排序,最后又遍历list,将结点的值改变
public ListNode sortList(ListNode head) {
ListNode cur = head;
List<Integer> list = new ArrayList<Integer>();
while (cur != null) {
list.add(cur.val);
cur = cur.next;
}
Collections.sort(list);
cur = head;
for (int i = 0; i < list.size(); i++) {
cur.val = list.get(i);
cur = cur.next;
}
return head;
}
法二:继续暴力
将链表的东西加入list,然后对list进行排序,之后将排好序的list串起来,使之成为一个类似链表的东西。
细节:
- 将list元素两两关联起来
- 返回的是list.get(0)
- 最后的那个元素要指向null!
// 返回排好序的列表
public ListNode sortList2(ListNode head) {
if (head == null) {
return head;
}
List<ListNode> list = new ArrayList<>();
while (head != null) {
list.add(head);
head = head.next;
}
Collections.sort(list, (n1, n2) -> n1.val - n2.val);
for (int i = 1; i < list.size(); i++) {
list.get(i - 1).next = list.get(i);
}
list.get(list.size() - 1).next = null;
return list.get(0);
}
还有归并排序的方法,待更新(我还没有掌握归并)
end.