Skip to content

Commit 424fcb8

Browse files
author
applewjg
committed
Insertion Sort List
Change-Id: I761fa5981176f1100aa0d622dbf05eadd89e4501
1 parent 09ec18b commit 424fcb8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

InsertionSortList.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Jan 02, 2015
4+
Problem: Insertion Sort List
5+
Difficulty: Easy
6+
Source: http://oj.leetcode.com/problems/insertion-sort-list/
7+
Notes:
8+
Sort a linked list using insertion sort.
9+
10+
Solution: ...
11+
*/
12+
/**
13+
* Definition for singly-linked list.
14+
* public class ListNode {
15+
* int val;
16+
* ListNode next;
17+
* ListNode(int x) {
18+
* val = x;
19+
* next = null;
20+
* }
21+
* }
22+
*/
23+
public class Solution {
24+
public ListNode insertionSortList(ListNode head) {
25+
if (head == null || head.next == null) return head;
26+
ListNode dummy = new ListNode(Integer.MIN_VALUE);
27+
dummy.next = head;
28+
ListNode cur = head.next;
29+
head.next = null;
30+
while (cur != null) {
31+
ListNode tmp = dummy;
32+
while (tmp.next != null && tmp.next.val <= cur.val) tmp = tmp.next;
33+
ListNode next = cur.next;
34+
cur.next = tmp.next;
35+
tmp.next = cur;
36+
cur = next;
37+
}
38+
return dummy.next;
39+
}
40+
}

0 commit comments

Comments
 (0)