-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathInsertionSortList.java
More file actions
88 lines (67 loc) · 1.72 KB
/
InsertionSortList.java
File metadata and controls
88 lines (67 loc) · 1.72 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package oj.leetcode;
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; next = null; } }
*/
public class InsertionSortList {
public static ListNode createListFromArray(int[] arr){
ListNode head = null;
for(int i = 0; i < arr.length; i++){
ListNode node = new ListNode(arr[i]);
node.next = head;
head = node;
}
return head;
}
public static void showList(ListNode head){
ListNode p = head;
while(p != null){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
// û��ͷ�ڵ㣬������������
public static ListNode insertionSortList2(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode p = head.next;
ListNode list = head; // construct a new list
list.next = null;
ListNode lo = list, pre = list;
while(p != null){
ListNode q = p;
p = p.next;
while(lo!= null && q.val > lo.val){
pre = lo;
lo = lo.next;
}
System.out.println("---------");
q.next = lo;
pre.next = q; //insert
lo = list; //next round
pre=list;
}
return list;
}
public static ListNode insertionSortList(ListNode head) {
ListNode list = new ListNode(0); //ͷ�ڵ�
while(head != null){
ListNode node = list;
while(node.next != null && node.next.val < head.val)
node = node.next;
ListNode tmp = head.next;
head.next = node.next;
node.next = head;
head = tmp;
}
return list.next;
}
public static void main(String[] args) {
int[] arr = {1,45,78,23,100,0,33,56,13,};
ListNode list =createListFromArray(arr);
showList(list);
list = insertionSortList(list);
showList(list);
}
}