c++ - 在链表类中实现 removeDuplicates() 方法
问题描述
#ifndef INT_LINKED_LIST
#define INT_LINKED_LIST
using namespace std;
class IntSLLNode {
public:
IntSLLNode() {
next = 0;
}
IntSLLNode(int el, IntSLLNode *ptr = 0) {
info = el; next = ptr;
}
int getInfo() const
{
return this->info;
}
IntSLLNode getNext() const
{
return this->next;
}
private:
int info;
IntSLLNode *next;
};
class IntSLList {
public:
IntSLList() {
head = tail = 0;
}
~IntSLList();
int isEmpty() {
return head == 0;
}
void addToHead(int);
void addToTail(int);
int deleteFromHead(); // delete the head and return its info;
int deleteFromTail(); // delete the tail and return its info;
void deleteNode(int);
bool isInList(int) const;
void removeDuplicates();
private:
IntSLLNode *head, *tail;
};
#endif
解决方案
简单的方法:删除除第一个元素之外的所有第一个元素,删除除第一个元素之外的所有第二个元素,……依此类推,直到您传递了最后一个元素。
假设你有
IntSLLNode* deduplicate(IntSLLNode* start)
start->info
从其后续节点中删除所有重复项并返回可能更新的尾指针,您可以编写
void removeDuplicates()
{
IntSLLNode* current = head;
while (current)
{
tail = deduplicate(current);
current = current->next;
}
}
实施deduplicate
左侧作为练习。
推荐阅读
- flutter - 如何在颤动中显示来自 path_provider 的视频?
- ruby-on-rails - 为什么 Heroku 安装我不使用的 gem?
- java - SocketException:FTP 上传时连接重置
- c++ - C++游戏中的UDP通信问题
- android - 评分栏在 android 中有 10 颗星
- npm - npm run scripts 运行无限时间
- javascript - × TypeError: Object(...) 不是函数
- javascript - Sanic Websocket 异步管理
- reactjs - 在设备视图之外反应原生模态内容
- django - Gunicorn 没有开始抛出 gunicorn.service:失败,结果为“退出代码”。错误