Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7bc5a35

Browse files
committed
sort
1 parent499a088 commit7bc5a35

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎list/InsertionSortList.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
packageAlgorithms.list;
2+
3+
importAlgorithms.algorithm.others.ListNode;
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* int val;
9+
* ListNode next;
10+
* ListNode(int x) {
11+
* val = x;
12+
* next = null;
13+
* }
14+
* }
15+
*/
16+
publicclassInsertionSortList {
17+
publicListNodeinsertionSortList(ListNodehead) {
18+
ListNodedummy =newListNode(0);
19+
20+
while (head !=null) {
21+
ListNodepre =dummy;
22+
23+
// 注意,这里要用<= 来保证算法的稳定性
24+
// 因为假如有2个数相同,后面的数后找到,也要插入到后面才可以。也就是说当=的时候,是继续往下走
25+
while (pre.next !=null &&pre.next.val <=head.val) {
26+
pre =pre.next;
27+
}
28+
29+
// unlink the node from the original link. And record the next position.
30+
ListNodeheadNext =head.next;
31+
head.next =pre.next;
32+
33+
pre.next =head;
34+
head =headNext;
35+
}
36+
37+
returndummy.next;
38+
}
39+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp