Given the head
of a linked list, return the list after sorting it in ascending order.
head
nodelinked list (?)
방법 1. Insertion Sort
방법 2. Marge Sort 일부 변형
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) { // 예외 처리 (0개, 1개)
return head;
}
ListNode beforeHead = sortList(head.next); // 뒤의 노드 정렬
if (head.val < beforeHead.val) { // head가 더 작으면
head.next = beforeHead;
return head;
}
ListNode beforeCurNode = beforeHead;
ListNode curNode = beforeHead.next;
while (curNode != null && head.val > curNode.val) { // 중간 삽입 위치 찾기
beforeCurNode = curNode;
curNode = curNode.next;
}
beforeCurNode.next = head; // 중간 노드 사이에 들어가기
head.next = curNode;
return beforeHead;
}
}
class Solution {
public ListNode sortList(ListNode head) {
if (head == null) {
return null;
}
Queue<ListNode> queue = new LinkedList<>();
ListNode inputNode = head;
while (inputNode != null) {
ListNode nextInputNode = inputNode.next;
queue.add(inputNode);
inputNode.next = null;
inputNode = nextInputNode;
}
while (queue.size() > 1) {
ListNode sortListNode = sortTwoSortedListByOne(queue.remove(), queue.remove());
queue.add(sortListNode);
}
return queue.remove();
}
private ListNode sortTwoSortedListByOne(ListNode node1, ListNode node2) {
ListNode head = node1;
if (node1.val <= node2.val) {
node1 = node1.next;
} else {
head = node2;
node2 = node2.next;
}
ListNode beforeNode = head;
ListNode currentNode;
while (node1 != null || node2 != null) {
if (node1 == null) {
currentNode = node2;
node2 = node2.next;
} else if (node2 == null) {
currentNode = node1;
node1 = node1.next;
} else if (node1.val <= node2.val) {
currentNode = node1;
node1 = node1.next;
} else {
currentNode = node2;
node2 = node2.next;
}
beforeNode.next = currentNode;
beforeNode = currentNode;
currentNode = null;
}
return head;
}
}
Marge Sort 이용 방법
Floyd's Cycle Detection Algorithm
slow
), 두 칸씩 이동하는 포인터(fast
)를 이용한다.slow
, fast
가 같은 객체를 가리키게 되면 해당 linked list가 순환한다.public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
// step 1. cut the list to two halves
ListNode prev = null, slow = head, fast = head;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
// step 2. sort each half
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
// step 3. merge l1 and l2
return merge(l1, l2);
}
ListNode merge(ListNode l1, ListNode l2) {
ListNode l = new ListNode(0), p = l;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if (l1 != null)
p.next = l1;
if (l2 != null)
p.next = l2;
return l.next;
}
}