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

C++Server Side ProgrammingProgramming

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

  • Initialise the linked list.
  • 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;
};
void addNewNode(struct Node **head, int data) {
   struct Node *newNode = new Node;
   newNode->data = data;
   newNode->next = *head;
   *head = newNode;
}
void moveZeroes(struct Node **head) {
   if (*head == NULL) {
      return;
   }
   struct Node *temp = (*head)->next, *prev = *head;
   while (temp != NULL) {
      if (temp->data == 0) {
         Node *current = temp;
         temp = temp->next;
         prev->next = temp;
         current->next = *head;
         *head = current;
      }else {
         prev = temp;
         temp = temp->next;
      }
   }
}
void printLinkedList(struct Node *head) {
   while (head != NULL) {
      cout << head->data << "->";
      head = head->next;
   }
   cout << "NULL" << endl;
}
int main() {
   struct Node *head = NULL;
   addNewNode(&head, 3);
   addNewNode(&head, 0);
   addNewNode(&head, 1);
   addNewNode(&head, 0);
   addNewNode(&head, 0);
   addNewNode(&head, 1);
   addNewNode(&head, 0);
   addNewNode(&head, 0);
   addNewNode(&head, 3);
   moveZeroes(&head);
   printLinkedList(head);
   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
raja
Updated on 25-Oct-2021 05:02:21

Advertisements