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

Commit 40a2e51

Browse files
committed
upload
1 parent 9006a52 commit 40a2e51

File tree

3 files changed

+54
-27
lines changed

3 files changed

+54
-27
lines changed
Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
19
class Solution {
210
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
3-
if (l1 == null) {
4-
return l2;
11+
ListNode head = new ListNode(0);
12+
head.next = null;
13+
ListNode current = head;
14+
while (l1 != null && l2 != null) {
15+
if (l1.val <= l2.val) {
16+
current.next = l1;
17+
l1 = l1.next;
18+
} else {
19+
current.next = l2;
20+
l2 = l2.next;
21+
}
22+
current = current.next;
523
}
6-
if (l2 == null) {
7-
return l1;
8-
}
9-
if (l1.val < l2.val) {
10-
l1.next = mergeTwoLists(l1.next, l2);
11-
return l1;
12-
}
13-
l2.next = mergeTwoLists(l1, l2.next);
14-
return l2;
24+
current.next = l1 != null ? l1 : l2;
25+
return head.next;
1526
}
1627
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public ListNode reverseList(ListNode head) {
11+
if (head == null) return null;
12+
ListNode reverse = null;
13+
while (head != null) {
14+
ListNode temp = head;
15+
head = head.next;
16+
if (reverse == null) {
17+
reverse = temp;
18+
temp.next = null;
19+
} else {
20+
temp.next = reverse;
21+
reverse = temp;
22+
}
23+
}
24+
return reverse;
25+
}
26+
}
Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,8 @@
1-
class Solution {
2-
public ListNode middleNode(ListNode head) {
3-
if (head == null || head.next == null) {
4-
return head;
5-
}
6-
ListNode fast = head;
7-
ListNode slow = head;
8-
while (fast.next != null) {
9-
// 快指针每次循环走两步,慢指针走一步
10-
fast = fast.next.next;
11-
slow = slow.next;
12-
if (fast == null || fast.next == null) {
13-
return slow;
14-
}
15-
}
16-
return null;
1+
public ListNode middleNode(ListNode head) {
2+
ListNode low = head, first = head;
3+
while (first != null && first.next != null) {
4+
low = low.next;
5+
first = first.next.next;
176
}
7+
return low;
188
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /