在 C 结构中找到相同的元素
Find the same elements in C-struct
我必须编写一个函数,该函数会将元素添加到C结构中,但它不能添加相同的元素。例:输入: 1 2 1 3
输出:
ADDED 1
ADDED 2
NOT ADD 1
ADD 3
元素取自数组,这是一段使用我需要编写的函数的代码:
int tab[] = {1,4,1,3,5};
Node* head = 0;
for (size_t i = 0, e = std::size(tab); i != e; ++i) {
bool b = add(head,tab[i]);
cout << tab[i] << (b ? " " : " NOT ")
<< "added" << endl;
}
C结构Node
看起来像这样:
struct Node {
int data;
Node* next;
};
这是我写的,但它添加了数组中的所有元素。我无法更改循环,只能更改add
功能:
bool add(Node*& head, int data){
Node *n = new Node;
n->data = data;
n->next = 0;
if(!head)
head = n;
else{
Node *tmp = head;
while(tmp->next)
tmp = tmp->next;
tmp->next = n;
}
};
目前您只需添加元素而不查看它是否已经存在
定义可以是这样的
bool add(Node*& head, int data){
if(!head) {
head = new Node;
n->data = data;
n->next = 0;
return true;
}
Node *tmp = head;
while (tmp->next) {
if (tmp->data == data)
return false;
tmp = tmp->next;
}
if (tmp->data == data)
return false;
tmp->next = new Node;
tmp->next->data = data;
tmp->next->next = 0;
return true;
}
我鼓励您添加一个构造函数,这样就不必在每次创建新实例后都设置数据和下一个字段
示例
Node::Node(int d) : next(0), data(d) {
}
// add should be a static method of Node, to be able to access next and data while they are private
bool add(Node*& head, int data){
if(!head) {
head = new Node(data);
return true;
}
Node *tmp = head;
while (tmp->next) {
if (tmp->data == data)
return false;
tmp = tmp->next;
}
if (tmp->data == data)
return false;
tmp->next = new Node(data);
return true;
}
这是我
的尝试。首先查找现有数据,如果不存在,则添加(与现有代码没有变化)
bool add(Node*& head, int data) {
Node *tmp = head;
while (tmp) {
if (tmp->data == data)
return false; // data already present
tmp = tmp->next;
}
Node *n = new Node;
n->data = data;
n->next = 0;
if (!head) {
head = n;
}
else {
Node *tmp = head;
while(tmp->next)
tmp = tmp->next;
tmp->next = n;
}
return true; // data added
}
所以我做了类似的事情,它适用于我拥有的数据。我想它一般有效
bool add(Node*& head, int data){
Node *n = new Node;
n->data = data;
n->next = 0;
if(!head)
head = n;
else{
Node *tmp = head;
while(tmp->next){
if(tmp->data == data)
return false;
else
tmp = tmp->next;
}
tmp->next = n;
}
};
相关文章:
- 使用不带参数的函数访问结构元素
- 带结构的二维矢量:如何存储元素
- 访问类lintalizer列表中的结构元素
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 设计将引用元素移动到开头的数据结构.C++
- 结构元素名称要 cout?
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 从指向结构数组的指针中提取元素
- 继承层次结构并将元素添加到向量
- 在集合中查找使用结构C++的元素
- C++结构元素(成员变量)的数量
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 在C++中更改结构内部元素的方法?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 如何为结构的数据元素赋值
- 如何使用矢量元素将项目添加到结构中?
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 指向结构的指针向量的元素具有相同的地址
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?