[LeetCode刷题] Insertion Sort List
这个是刷的第一题,medium难度。算法没什么难度,主要是有一个edge case。maintain两个list,第一个是sort好的,第二个是没sort得部分。值得重新做的一个题目,有些小技巧在下面另一个解法讲。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null) {
return null;
}
ListNode ret = head;
ListNode cur = head.next;
ret.next = null;
while(cur != null) {
ListNode rCur = ret;
boolean found = false;
while(rCur.next != null) {
if(cur.val <= rCur.val) {
//Insert to head
ListNode temp = cur.next;
cur.next = rCur;
ret = cur;
cur = temp;
found = true;
break;
}
if(cur.val >= rCur.val && cur.val <= rCur.next.val) {
//insert to middle
ListNode temp = cur.next;
cur.next = rCur.next;
rCur.next = cur;
cur = temp;
found = true;
break;
}
rCur = rCur.next;
}
if(!found) {
if(cur.val <= rCur.val) {//edge case, 如果出现这样的情况,说明这整个list只有两个元素。
ListNode temp = cur.next;
cur.next = rCur;
ret = cur;
cur = temp;
} else {
//insert to tail
ListNode temp = cur.next;
cur.next = null;
rCur.next = cur;
cur = temp;
}
}
}
return ret;
}
}
看到了一个别人更好的解法,使用了一个helper在head之前,这样少了那个edge case,简便了很多
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null) {
return null;
}
//这里用一个技巧,省去了head的edge case
ListNode helper = new ListNode(0);
//这样cur直接定在head即可
ListNode cur = head;
ListNode pre;
while(cur != null) {
ListNode next = cur.next;
pre = helper;
//注意这里的比较,找insert的position时,比较只需要比后面一个与cur的大小
while(pre.next != null && pre.next.val <= cur.val) {
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
cur = next;
}
return helper.next;
}
}