在 C++ 中將所有零移動到連結串列的前面


給定一個包含隨機整數和零的連結串列。我們需要將所有零移動到連結串列的前面。讓我們看一個例子。

輸入

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

輸出

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

演算法

  • 初始化連結串列。
  • 如果連結串列為空或只有一個節點,則返回。
  • 分別用第二個節點和第一個節點初始化兩個節點,以跟蹤當前節點和前一個節點。
  • 迭代連結串列,直到到達末尾。

    • 如果當前節點為 0,則將其設為新的頭部。
    • 更新當前節點和前一個節點變數的值。
    • 將節點設為新的頭部會將其移動到前面。
    • 更新新頭部的下一個節點的值為前一個頭部。

實現

以下是 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;
}

輸出

如果您執行以上程式碼,則將獲得以下結果。

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

更新於: 2021-10-25

277 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.