21. Merge Two Sorted Lists

Easy

Problem:

Merge two sorted linked lists.

Input: list1 = [1,2,4], list2 = [1,3,4] 
Output: [1,1,2,3,4,4]

https://leetcode.com/problems/merge-two-sorted-lists/arrow-up-right

What to learn:

Precedence of Python Operators

Operators
Meaning

()

Parentheses

**

Exponent

+x, -x, ~x

Unary plus, Unary minus, Bitwise NOT

*, /, //, %

Multiplication, Division, Floor division, Modulus

+, -

Addition, Subtraction

<<, >>

Bitwise shift operators

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in

Comparisons, Identity, Membership operators

not

Logical NOT

and

Logical AND

or

Logical OR

lambda

Lambda function

Solution:

Recursive

First, compare the values of list1 and list2, and make the smaller value come to the left. Then, call recursively so that 'next' links to the following value.

chevron-rightSwap two variableshashtag

When swapping numbers, it can be solved without requiring additional space by using a simple mathematical approach. Here's how you can do it in Python:

Last updated