首頁  >  文章  >  後端開發  >  C++程式:將鍊錶中的重複節點替換為副本

C++程式:將鍊錶中的重複節點替換為副本

王林
王林轉載
2023-08-27 08:41:141102瀏覽

C++程式:將鍊錶中的重複節點替換為副本

在本文中,我們給出了一個鍊錶,其中包含從 1 到 n 的元素以及重複項。元素 1 到 n 將始終與 [1..n] 中的重複項存在。我們需要用 n 1、n 2 等來取代每個重複元素。

讓我們考慮一個例子

1→2→2→4→5→3→6→6

#接下來 n = 42。因此,每個重複項都會被替換為 n 1、n 2 等。接下來的 42 被替換為 47,接下來的 46 被替換為 48,第一個實例保持原樣。

首先,我們需要在main方法中建構一個二元樹,如下所示 -

Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(2);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head->next->next->next->next->next = new Node(3);
head->next->next->next->next->next->next = new Node(6);
head->next->next->next->next->next->next->next = new Node(6);
solve(head);

現在節點如下;

1→2→7→4→5→3→6→8

#正如我們所觀察到的,我們需要追蹤我們看到的元素以找到 n 的起始值。我們還需要一種機制來確定哪些元素被重複以替換它們的值。

立即想到的建議資料結構已確定。我們可以遍歷鍊錶並將元素推入集合中。將集合中的元素壓入後,我們可以找到最後一個元素,即鍊錶中可用的最大元素,因為集合是排序的資料結構。

在鍊錶的第二次遍歷中,我們可以使用集合作為雜湊。我們將搜尋集合中的每個元素,可能會出現兩種情況。

  • 我們在集合中找到該元素,然後將其從集合中刪除,並對其進行標記。

  • 我們在集合中沒有找到該元素,這意味著我們已經從選項一中看到了它,我們將用下一個 n 取代它。

範例

要實作替換鍊錶中重複值的節點,請依照下面的 C 程式進行操作。 C 實作利用集合資料結構來遍歷鍊錶,有助於搜尋重複元素。

#include <iostream>
#include <set>
using namespace std;
class Node {
   public:
   int value;
   Node* next;
   Node(int value) {
      this->value = value;
      next = NULL;
   }
};
void solve(Node* head) {
   set<int> hash;
   Node* copy = head;
   while(copy) {
      hash.insert(copy->value);
      copy = copy->next;
   }
   auto it = hash.end();
   it--;
   int startingN = *it +1;
   while(head) {
      if(hash.find(head->value) != hash.end()) {
         hash.erase(head->value);
      } else {
         head->value = startingN++;
      }
      head = head->next;
   }
}
void printList(Node* head) {
   while(head) {
      cout << head->value << " ";
      head = head->next;
   }
}
int main() {
   Node* head = new Node(41);
   head->next = new Node(42);
   head->next->next = new Node(42);
   head->next->next->next = new Node(44);
   head->next->next->next->next = new Node(45);
   head->next->next->next->next->next = new Node(43);
   head->next->next->next->next->next->next = new Node(46);
   head->next->next->next->next->next->next->next = new Node(46);
   cout << "Before: ";
   printList(head);
   cout << "\n";
   solve(head);
   cout << "After: ";
   printList(head);
   return 0;
}

輸出

Before: 41 42 42 44 45 43 46 46
After: 41 42 47 44 45 43 46 48  

結論

我們使用了雜湊的概念,並藉助資料結構集找到了鍊錶中最大的元素。我們也可以使用 map 或 unordered_map 作為哈希。

以上是C++程式:將鍊錶中的重複節點替換為副本的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除