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

Commit248e31f

Browse files
committed
sort
1 parentfa4cbba commit248e31f

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

‎list/SortList.java

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
packageAlgorithms.list;
2+
3+
importAlgorithms.algorithm.others.ListNode;
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* class ListNode {
8+
* int val;
9+
* ListNode next;
10+
* ListNode(int x) {
11+
* val = x;
12+
* next = null;
13+
* }
14+
* }
15+
*/
16+
publicclassSortList {
17+
publicListNodesortList(ListNodehead) {
18+
// Nodes should be more than 2.
19+
if (head ==null ||head.next ==null) {
20+
returnhead;
21+
}
22+
23+
// get the mid node.
24+
ListNodemidPre =getMidPre(head);
25+
26+
// Cut the two list.
27+
ListNoderight =midPre.next;
28+
midPre.next =null;
29+
30+
// Sort the left side and the right side.
31+
ListNodeleft =sortList(head);
32+
right =sortList(right);
33+
34+
// Merge the two sides together.
35+
returnmerge(left,right);
36+
}
37+
38+
// get the pre node before mid.
39+
publicListNodegetMidPre1(ListNodehead) {
40+
ListNodeslow =head;
41+
ListNodefast =head;
42+
43+
while (fast !=null &&fast.next !=null &&fast.next.next !=null) {
44+
slow =slow.next;
45+
fast =fast.next.next;
46+
}
47+
48+
returnslow;
49+
}
50+
51+
// get the pre node before mid.
52+
publicListNodegetMidPre(ListNodehead) {
53+
ListNodeslow =head;
54+
55+
// fast提前一点儿。这样就可以得到前一个节点喽。
56+
ListNodefast =head.next;
57+
58+
while (fast !=null &&fast.next !=null) {
59+
slow =slow.next;
60+
fast =fast.next.next;
61+
}
62+
63+
returnslow;
64+
}
65+
66+
publicListNodemerge(ListNodehead1,ListNodehead2) {
67+
ListNodedummy =newListNode(0);
68+
ListNodecur =dummy;
69+
70+
while (head1 !=null &&head2 !=null) {
71+
if (head1.val <head2.val) {
72+
cur.next =head1;
73+
head1 =head1.next;
74+
}else {
75+
cur.next =head2;
76+
head2 =head2.next;
77+
}
78+
79+
cur =cur.next;
80+
}
81+
82+
if (head1 !=null) {
83+
cur.next =head1;
84+
}else {
85+
cur.next =head2;
86+
}
87+
88+
returndummy.next;
89+
}
90+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp