-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path0147.对链表进行插入排序.java
102 lines (97 loc) · 2.37 KB
/
0147.对链表进行插入排序.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* @lc app=leetcode.cn id=147 lang=java
*
* [147] 对链表进行插入排序
*
* https://leetcode.cn/problems/insertion-sort-list/description/
*
* algorithms
* Medium (69.22%)
* Likes: 558
* Dislikes: 0
* Total Accepted: 136.2K
* Total Submissions: 196.7K
* Testcase Example: '[4,2,1,3]'
*
* 给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头 。
*
* 插入排序 算法的步骤:
*
*
* 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
* 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
* 重复直到所有输入数据插入完为止。
*
*
*
* 下面是插入排序算法的一个图形示例。部分排序的列表(黑色)最初只包含列表中的第一个元素。每次迭代时,从输入数据中删除一个元素(红色),并就地插入已排序的列表中。
*
* 对链表进行插入排序。
*
*
*
*
*
* 示例 1:
*
*
*
*
* 输入: head = [4,2,1,3]
* 输出: [1,2,3,4]
*
* 示例 2:
*
*
*
*
* 输入: head = [-1,5,3,4,0]
* 输出: [-1,0,3,4,5]
*
*
*
* 提示:
*
*
*
*
* 列表中的节点数在 [1, 5000]范围内
* -5000 <= Node.val <= 5000
*
*
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public 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) {
if (head == null || head.next == null)
return head;
ListNode dummy = new ListNode();
ListNode current = head, node;
while (current != null) {
node = current.next;
// 将当前节点从链表中摘除
current.next = null;
// 找到新的位置并插入
ListNode pre = dummy, ln = dummy.next;
while (ln != null && ln.val < current.val) {
ln = ln.next;
pre = pre.next;
}
current.next = pre.next;
pre.next = current;
current = node;
}
return dummy.next;
}
}
// @lc code=end