-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSortList_147.java
45 lines (41 loc) · 1.12 KB
/
InsertionSortList_147.java
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Insertion Sort: insert to the right position
* Bubble Sort: swap between elements
* Selection Sort: select the next element
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode curr = head, newhead = null, next = null;
while(curr!=null) {
next = curr.next;
newhead = findPos(newhead, curr);
curr = next;
}
return newhead;
}
private ListNode findPos(ListNode head, ListNode insert) {
ListNode dhead = new ListNode(0);
dhead.next = head;
ListNode curr = head, prev = dhead;
while(curr!=null) {
if (curr.val >= insert.val) {
prev.next = insert;
insert.next = curr;
return dhead.next;
}
prev = curr;
curr = curr.next;
}
prev.next = insert;
insert.next = null;
return dhead.next;
}
}