-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sortlist.java
More file actions
48 lines (46 loc) · 1.31 KB
/
insertion_sortlist.java
File metadata and controls
48 lines (46 loc) · 1.31 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
/*
Insertion Sort List
Sort a linked list using insertion sort.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newhead = new ListNode(Integer.MIN_VALUE);
newhead.next = head;
ListNode begin = head.next;
head.next = null; // cut the list, in case of infinite loop.
while(begin != null){
ListNode tem = newhead;
while(tem.next != null){
if(tem.next.val < begin.val){
tem = tem.next;
}else{
break;
}
}
if(tem.next == begin){
// tem.val < begin.val, do not need to change position.
tem.next = begin;
begin = begin. next;
}else{
// change position (tem.next and begin)
ListNode node = begin.next;
begin.next = tem.next;
tem.next = begin;
begin = node;
}
}
return newhead.next;
}
}