-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathT5.java
More file actions
54 lines (48 loc) · 1.53 KB
/
T5.java
File metadata and controls
54 lines (48 loc) · 1.53 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
package testCode;
public class T5 {
public static void main(String[] args) {
System.out.println("Hello World!");
ListNode head = new ListNode(2);
head.next = new ListNode(3);
head.next.next = new ListNode(1);
System.out.print(insertionSortList(head).val);
}
public static ListNode insertionSortList(ListNode head) {
if (null == head || null == head.next) {
return head;
}
ListNode currentNode = head;
ListNode nextNode = head.next;
while (null != nextNode) {
if (currentNode.val > nextNode.val) {
if (head.val > nextNode.val) {
currentNode.next = nextNode.next;
nextNode.next = head;
head = nextNode;
nextNode = currentNode.next;
} else {
ListNode p = head;
while (p.next.val < nextNode.val) {
p = p.next;
}
currentNode.next = nextNode.next;
nextNode.next = p.next;
p.next = nextNode;
nextNode = currentNode.next;
}
} else {
currentNode = nextNode;
nextNode = nextNode.next;
}
}
return head;
}
private static class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}