在 C 结构中找到相同的元素

Find the same elements in C-struct

本文关键字:元素 结构      更新时间:2023-10-16

我必须编写一个函数,该函数会将元素添加到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;
}
};