-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path147.对链表进行插入排序.java
43 lines (40 loc) · 1.08 KB
/
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
/*
* @lc app=leetcode.cn id=147 lang=java
*
* [147] 对链表进行插入排序
*/
// @lc code=start
/**
* Definition for singly-linked list.
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode toInsert = head.next;
head.next = null;
while(toInsert != null){
ListNode next = toInsert.next;
if(toInsert.val <= head.val){
toInsert.next = head;
head = toInsert;
toInsert = next;
continue;
}
ListNode preInsertNode = head;
while(preInsertNode.next != null && toInsert.val > preInsertNode.next.val){
preInsertNode = preInsertNode.next;
}
toInsert.next = preInsertNode.next;
preInsertNode.next = toInsert;
toInsert = next;
}
return head;
}
}
// @lc code=end