Skip to content

Commit 0c1c383

Browse files
committed
add test case and ListNode traverse method
1 parent ec8e39d commit 0c1c383

File tree

3 files changed

+42
-11
lines changed

3 files changed

+42
-11
lines changed

LeetCode/0021. Merge Two Sorted Lists/src/Solution.java

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/**
22
* @author Changle
33
* @date 2019/6/26 9:36
4-
* source: https://leetcode.com/problems/merge-two-sorted-lists/
4+
* source: <a href="https://leetcode.com/problems/merge-two-sorted-lists/">https://leetcode.com/problems/merge-two-sorted-lists/</a>
55
* T(n): O(l1.len + l2.len)
66
* S(n): O(l1.len + l2.len)
77
*/
@@ -21,16 +21,7 @@ public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
2121
}
2222
cur = cur.next;
2323
}
24-
while (l1 != null) {
25-
cur.next = l1;
26-
l1 = l1.next;
27-
cur = cur.next;
28-
}
29-
while (l2 != null) {
30-
cur.next = l2;
31-
l2 = l2.next;
32-
cur = cur.next;
33-
}
24+
cur.next = l1 == null ? l2 : l1;
3425

3526
return dummy.next;
3627

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @author clz
3+
* @date 2022/4/16
4+
*
5+
*/
6+
public class TestCase {
7+
8+
public static void main(String[] args) {
9+
ListNode l11 = new ListNode(-9);
10+
l11.next = new ListNode(3);
11+
ListNode l21 = new ListNode(5);
12+
l21.next = new ListNode(7);
13+
Solution solution = new Solution();
14+
ListNode listNode = solution.mergeTwoLists(l11, l21);
15+
listNode.traverse();
16+
}
17+
18+
}

LeetCode/src/ListNode.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,36 @@
1+
import java.util.List;
2+
13
/**
24
* @author changleamazing
35
* @date 2019/12/18 23:15
46
**/
57
public class ListNode {
68

9+
final String separator = " -> ";
710
int val;
811
ListNode next;
912

1013
ListNode(int x) {
1114
val = x;
1215
}
16+
17+
ListNode(int val, ListNode next) {
18+
this.val = val;
19+
this.next = next;
20+
}
21+
22+
public void traverse() {
23+
StringBuilder res = new StringBuilder();
24+
ListNode cur = this;
25+
while (cur != null) {
26+
if (cur.next == null) {
27+
res.append(cur.val).append(";");
28+
}else {
29+
res.append(cur.val).append(separator);
30+
}
31+
cur = cur.next;
32+
}
33+
System.out.println(res);
34+
}
1335
}
1436

0 commit comments

Comments
 (0)