在 C++ 中将所有零移动到链表的前面

在本教程中,我们将编写一个程序,将所有零移动到给定链表的前面。

让我们看看解决问题的步骤。

  • 初始化链表。

  • 用第二个节点和第一个节点初始化两个节点。

  • 遍历链表。

    • 当前节点元素为0时。

    • 将它移到前面并使其成为新的头部。

示例

让我们看看代码。

#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;
}
输出结果

如果你运行上面的代码,那么你会得到下面的结果。

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

结论

如果您对本教程有任何疑问,请在评论部分提及。