LeetCode add two numbers : explanations and solutions with Cpp/Java/Python
An sample input:
This problem tests the skills of linked list operation. Two points need to notice here:
- How to merge two linked list into one
- How to use a dummy node to simplify code logic
Merge two linked lists
It’s straightforward to iterate over two node pointers. But please notice the scenario of one linked list is longer than the other one. We need to make sure a node is valid before using it. This is error-prone for starter.
Assume that $m$ and $n$ represents the length of $l1$ and $l2$ respectively:
The time complexity: $O(max(M, N))$
The space complexity: $O(max(M, N))$
Use the dummy node
If we don’t use
dummy node, we must have a variable which pointing to the final result. If we don’t initialize it beforehand, we need to construct it during the loop. the pseudo code should be:
Hence the code is a little complicated, and it’s also mixed with other logic for merging node.
The idea of
dummy node is we initialize a unused node firstly, then we always keep the dummy.next to be the head node. This is good taste for linked list.
Notice this Java version don’t test the sum >= 10, I keep it in C++ version for a little better time performance.
Preparing for an interview? Check out this!
Join my Email List for more insights, It's Free!😋