刷題日記(2)Merge Two Sorted Lists

Rachel Yeh
2 min readDec 19, 2020

Merge two sorted linked lists and return it as a new sortedlist. The new list should be made by splicing together the nodes of the first two lists.

Example 1:

Input: l1 = [1,2,4], l2 = [1,3,4]

Output: [1,1,2,3,4,4]

Example 2:

Input: l1 = [], l2 = []

Output: []

Example 3:

Input: l1 = [], l2 = [0]

Output: [0]

Constraints:

The number of nodes in both lists is in the range [0, 50].

-100 <= Node.val <= 100

Both l1 and l2 are sorted in non-decreasingorder.

解題思路

1. 設dummy和last node

2. 比大小接到dummy next,移動last node

3. 當L1或L2其中一者為null時則把剩下的接到last node的後面

(main Function)

  1. 設dummy node (類似衛兵的概念)

2. 再設一個last node的標籤給dummy node

3. 當L1和L2都不為null時

3.1 如果L2的值大於L1時

3.1.1 Last Node的next 等於L1

3.1.2 L1 等於L1的next (L1進一格)

3.2 其他

3.2.1 Last Node的Next等於L2

3.2.2 L2等於L2的next (L2進一格)

4. 如果L1或L2一者為null則會跳出迴圈

4.1 如果L1不為null, 則last node的Next等於 L1

4.2 其他的話 last node 的Next等於 L2

4.3 意思就是把剩下的尾巴接到已經排好的List後面

5. 回傳dummy node的下一個

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Rachel Yeh
Rachel Yeh

Written by Rachel Yeh

Taiwan /Software Engineer / Cryptoer

No responses yet

Write a response