FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_118/leetcode_21_118.java at master · kdbreboot/algorithm · GitHub
kdbreboot
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_118
/
leetcode_21_118.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
53 lines (46 loc) · 1.56 KB
Breadcrumbs
algorithm
/
Week_01
/
id_118
/
leetcode_21_118.java
Copy path
File metadata and controls
53 lines (46 loc) · 1.56 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/**
*
* https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/
*
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class
Solution
{
public
ListNode
mergeTwoLists
(
ListNode
l1
,
ListNode
l2
) {
// 1. 边界处理:两个都为null或任意一个为null
if
(
l1
==
null
||
l2
==
null
){
return
l1
==
null
?
l2
:
l1
;
}
// 2. 初始化新链表中的节点。
// - 为了简化处理,初始化一个头结点作为哨兵节点,值为0。
// - 再初始化一个临时指针,指向头结点,从头开始往链表上挂节点。
ListNode
head
=
new
ListNode
(
0
);
ListNode
current
=
head
;
// 3. 同时遍历两个链表,哪个头结点值最小,则把哪个节点的头拆下来
// - 注意,拆头结点的时候,千万别把指针拆丢了
while
(
l1
!=
null
&&
l2
!=
null
){
if
(
l1
.
val
<=
l2
.
val
){
current
.
next
=
l1
;
l1
=
l1
.
next
;
}
else
{
current
.
next
=
l2
;
l2
=
l2
.
next
;
}
current
=
current
.
next
;
current
.
next
=
null
;
}
// 4. 边界处理:可能某一个指针还没走完,直接无脑追加上就好了
if
(
l1
!=
null
){
current
.
next
=
l1
;
}
if
(
l2
!=
null
){
current
.
next
=
l2
;
}
// 5. 最后,返回 head.next,因为head节点数据无意义
return
head
.
next
;
}
}
Back
|
FazBrowse Home
|
New Git URL