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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that moves all zeroes to the front in the given linked list.

Let's see the steps to solve the problem.

  • Initialise the linked list.

  • Initialise two node with second node and first node.

  • Iterate over the linked list.

    • When the current node element is 0.

    • Move it to the front and make it as new head.

Example

Let's see the code.

 Live Demo

#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

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Jul-2021 06:39:36
Advertisements