Sort List
147. Insertion Sort List
Given the head
of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
It repeats until no input elements remain.
My Solutions:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
// curr用来遍历所有node,pre用来标记linkedlist的开头
ListNode curr = head, pre = dummy;
while (curr != null && curr.next != null) {
if (curr.val <= curr.next.val) {
curr = curr.next;
} else {
pre = dummy; // 重置pre的位置
ListNode temp = curr.next; // 用来标记需要移动的node
curr.next = temp.next;
// 把pre移动到需要插入位置的前一位
while (pre.next.val <= temp.val) {
pre = pre.next;
}
// 把temp连接上
temp.next = pre.next;
pre.next = temp;
}
}
return dummy.next;
}
}
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
My Solutions:
用merge sort的思想
找中点分开
merge
Time: O(nlgn); Space: O(n)
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode middle = findMiddle(head);
ListNode secondHalf = middle.next;
middle.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(secondHalf);
return merge(l1, l2);
}
private ListNode findMiddle(ListNode head) {
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
node.next = l1;
l1 = l1.next;
} else {
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if (l1 != null) node.next = l1;
else node.next = l2;
return dummy.next;
}
}
Last updated