LeetCode Linked List Question Summary
Xiahua Liu November 09, 2024 #LeetCode #C++ #Algorithm #Linked ListAfter solved around 20 questions on leetcode about linked list, I think it is time to summarize everything I learned so far:
Type Definition
It is usually defined as:
Linked List Traversal
It is important to know whether you want to traverse a linked list in pre order or post order.
Pre-Order Traversal
Iterative style
The logic is very simple:
for
If we need to visit 2 nodes at once (like manipulating the link), use prev
pointer to store the last visited node.
ListNode* prev = nullptr;
for
Recursive style
void
If 2 nodes are needed inside a loop:
void
;
Post-Order Traversal
This type of traversal is only viable through either a stack
or recursive functions.
We process the end node first, and go back to the head node one by one.
Iterative style
In order to interatively do the post-order traversal, a stack
is needed at the beginning.
auto next = stack<ListNode*>;
// First push all nodes to a stack
for
// Pop one by one
while
If 2 node is needed, you can push a nullptr
at the bottom, and check if nullptr
is at the top during the loop:
auto next = stack<ListNode*>;
// First push all nodes to a stack
for
// Pop one by one
while
Recursive style
You can also do the post order traversal in the recursive style:
void
Notice the difference between the pre and post order traversal because they are very similar here.
For post-order traversal, we first call the recursive function, then do something to the current node.
2-node post-order traversal:
void
;
Example
A good example to use all of above things we dicussed is LeetCode question 206: Reverse Linked List.
Pre-Order Traversal Solution
Because we need to visit 2 nodes at once:
Iterative style
ListNode*
ListNode*
Recursive style
ListNode*
ListNode*
Post-Order Traversal Solution
Iterative style
ListNode*
ListNode*
Recursive style
void
ListNode*
Create a Linked List
Always add a dummy node at the beginning for null case.