-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort.java
More file actions
50 lines (43 loc) · 1.02 KB
/
InsertSort.java
File metadata and controls
50 lines (43 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class InsertSort {
public class ListNode {
int val;
ListNode next;
ListNode(int x){
val = x;
next = null;
}
}
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode real = new ListNode(head.val);
dummy.next = real;
ListNode pointer = head.next;
while (pointer != null) {
ListNode prev = dummy;
ListNode cur = dummy.next;
while (cur != null && cur.val <= pointer.val) {
cur = cur.next;
prev = prev.next;
}
prev.next = new ListNode(pointer.val);
prev = prev.next;
prev.next = cur;
pointer = pointer.next;
}
return dummy.next;
}
public void testInsertion() {
ListNode head = new ListNode(5);
head.next = new ListNode(3);
head.next.next = new ListNode(9);
head.next.next.next = new ListNode(1);
ListNode newHead = insertionSortList(head);
while (newHead != null) {
System.out.print(newHead.val + " ");
newHead = newHead.next;
}
}
}