Skip to content

Commit 5b197f6

Browse files
authored
Create InsertionSortList.java
1 parent 026e84e commit 5b197f6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

medium/InsertionSortList.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//147. Insertion Sort List
2+
/**
3+
* Definition for singly-linked list.
4+
* public class ListNode {
5+
* int val;
6+
* ListNode next;
7+
* ListNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public ListNode insertionSortList(ListNode head) {
12+
ListNode fakeHead = new ListNode(Integer.MIN_VALUE);
13+
while (head != null){
14+
ListNode p = fakeHead;
15+
while (p != null) {
16+
if ( head.val >= p.val && (p.next == null || head.val <= p.next.val)) {
17+
ListNode next = head.next;
18+
head.next = p.next;
19+
p.next = head;
20+
head = next;
21+
break;
22+
}
23+
p = p.next;
24+
}
25+
}
26+
return fakeHead.next;
27+
}
28+
}

0 commit comments

Comments
 (0)