# Move all zeros to the front of the linked list in C++

Given a linked list with random integers and zeroes. We have to move all the zeroes to the front of the linked list. Let's see an example.

Input

3 -> 0 -> 1-> 0 -> 0 -> 1 -> 0 -> 0 -> 3 -> NULL

Output

0->0->0->0->0->3->1->1->3->NULL


## Algorithm

• Return if the linked list is empty or it has single node.
• Initialise two nodes with second node and first node respectively to track current and previous nodes.
• Iterate over the linked list until we reach the end.

• If the current node is 0, then make it new head.
• Update the values of current and previous nodes variables.
• Making the node new head will move it to the front.
• Update the next value of the new head with the previous head.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node *newNode = new Node;
newNode->data = data;
}
return;
}
while (temp != NULL) {
if (temp->data == 0) {
Node *current = temp;
temp = temp->next;
prev->next = temp;
}else {
prev = temp;
temp = temp->next;
}
}
}
}
cout << "NULL" << endl;
}
int main() {
return 0;
}

## Output

If you run the above code, then you will get the following result.

0->0->0->0->0->3->1->1->3->NULL

Updated on: 25-Oct-2021

163 Views 