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作为哈希表。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP