700697. Move all zeros to the front of the linked list
Here is the detailed Markdown blog post for the problem "Move all zeros to the front of the linked list":
Move all zeros to the front of the linked list
Summary
This problem involves manipulating a linked list by moving all the zero nodes to the front while preserving the order of non-zero nodes. The task requires implementing an algorithm that can efficiently rearrange the linked list.
Detailed Explanation
To solve this problem, we'll use a simple two-pointer approach. We'll maintain two pointers, p1 and p2, initially pointing to the start of the linked list. We'll iterate through the list, moving nodes with values other than zero to the front by updating p1. When we encounter a node with value zero, we'll move it to the front by updating both p1 and p2.
Here's a step-by-step breakdown of the algorithm:
- Initialize
p1andp2to point to the start of the linked list. - Iterate through the list:
- If the current node's value is not zero, move it to the front by updating
p1. - If the current node's value is zero, move it to the front by updating both
p1andp2.
- If the current node's value is not zero, move it to the front by updating
- When the iteration ends,
p1will point to the start of the modified linked list with all zeros at the front.
Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we only use a few extra variables to store the pointers.
Optimized Solutions
Java
public class Solution {
public ListNode moveZerosToStart(ListNode head) {
ListNode p1 = head, p2 = head;
while (p2 != null && p2.next != null) {
if (p2.val == 0) {
p1 = p2;
}
p2 = p2.next;
}
return p1;
}
}