FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

合并两个有序链表 · feixiangcode/algorithm@e2e3d01 · GitHub

Commit e2e3d01

Browse files
suncen
committed
合并两个有序链表
1 parent 486f4a4 commit e2e3d01

3 files changed

Lines changed: 46 additions & 1 deletion

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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 mergeTwoLists(ListNode l1, ListNode l2) {
11+
//创建一个新的listnode
12+
//两个有序的listnode每个取一个,比较,并加入新的Listnode
13+
ListNode listNode = new ListNode(0);
14+
ListNode current = listNode;
15+
while (l1 != null && l2 != null) {
16+
if (l1.val < l2.val) {
17+
//l1加入listnode l1位置后移
18+
current.next = l1;
19+
current = l1;
20+
l1 = l1.next;
21+
22+
} else {
23+
//l2加入listnode l2位置后移
24+
current.next = l2;
25+
current = l2;
26+
l2 = l2.next;
27+
28+
}
29+
30+
}
31+
32+
if (l1 == null) {
33+
current.next = l2;
34+
}
35+
if (l2 == null) {
36+
current.next = l1;
37+
}
38+
39+
return listNode.next;
40+
}
41+
}

‎Week_01/id_126/NOTE.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
# 学习笔记
1+
# 学习笔记
2+
3+
解题思路:
4+
技巧一:初始化的时候把head节点初始化一个给定的值,这样,后续操作就不用考虑头节点问题,直接排序好了,把最小的赋值给head.next就可以了。
5+
技巧二:两个链表为空和不为空的判断,循环逻辑依赖判断条件

‎Week_01/id_126/test.txt‎

Whitespace-only changes.

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL