題目資訊
難度: easy
使用語言: python、javascript
題目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
想法
很簡單的依照大小作排列
要注意長度不一樣長的時候,結束 while
後要補尾吧
Code
Python
1 | # Definition for singly-linked list. |
2 | # class ListNode: |
3 | # def __init__(self, x): |
4 | # self.val = x |
5 | # self.next = None |
6 | |
7 | class Solution: |
8 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: |
9 | if not (l1 or l2): |
10 | return None |
11 | if not l1: |
12 | return l2 |
13 | if not l2: |
14 | return l1 |
15 | head=now = ListNode(0) |
16 | while l1 and l2: |
17 | if l1.val <= l2.val: |
18 | now.next = ListNode(l1.val) |
19 | l1 = l1.next |
20 | else: |
21 | now.next = ListNode(l2.val) |
22 | l2 = l2.next |
23 | now=now.next |
24 | if l1: |
25 | now.next = l1 |
26 | elif l2: |
27 | now.next = l2 |
28 | return head.next |
Javascript
1 | /** |
2 | * Definition for singly-linked list. |
3 | * function ListNode(val) { |
4 | * this.val = val; |
5 | * this.next = null; |
6 | * } |
7 | */ |
8 | /** |
9 | * @param {ListNode} l1 |
10 | * @param {ListNode} l2 |
11 | * @return {ListNode} |
12 | */ |
13 | var mergeTwoLists = function(l1, l2) { |
14 | const head = now = new ListNode(0); |
15 | while(l1 && l2){ |
16 | if (l1.val <= l2.val){ |
17 | now.next = new ListNode(l1.val); |
18 | l1 = l1.next; |
19 | } |
20 | else{ |
21 | now.next = new ListNode(l2.val); |
22 | l2 = l2.next; |
23 | } |
24 | now = now.next |
25 | } |
26 | if(l1){ |
27 | now.next = l1; |
28 | } |
29 | else if(l2){ |
30 | now.next = l2; |
31 | } |
32 | return head.next |
33 | }; |