C++程式:替換連結串列中重複的節點


本文介紹了一個包含1到n的元素以及重複元素的連結串列。元素1到n總是存在,並且包含[1..n]範圍內的重複元素。我們需要將每個重複元素替換為n+1、n+2等。

讓我們來看一個例子

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

假設n = 6。因此,每個重複元素都將被替換為n+1、n+2等等。下一個6將被替換為7,下一個7將被替換為8,保留第一個例項不變。

首先,我們需要像下面這樣在主方法中構造一個二叉樹:

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的起始值。我們還需要一種機制來找出哪些元素是重複的,以便替換它們的值。

一個立即想到的合適資料結構是集合(set)。我們可以遍歷連結串列並將元素推入集合中。將元素推入集合後,我們可以找到最後一個元素,即連結串列中最大的可用元素,因為集合是一個排序的資料結構。

在連結串列的第二次遍歷中,我們可以使用集合作為雜湊表。我們將搜尋集合中的每個元素,並且可能出現兩種情況。

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

  • 我們在集合中找不到該元素,這意味著我們已經從情況一中看到了它,我們將用下一個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作為雜湊表。

更新於:2022年8月10日

瀏覽量:338

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.