如何在c++中避免相同的输入id值

  • 本文关键字:id c++ c++ input linked-list
  • 更新时间 :
  • 英文 :


如何避免链表中的双id,例如,我有id, name, gol,所以首先,我输入id= 12, name=jon gol=A,当我再次输入时。id = 12,其显示消息"id不能same"。再次输入

这是我的代码插入链表第一个节点,

#include <iostream>
#include <string>
#include <conio.h>
struct node {
int id;
char name[20], gol;
node *next;
};
node *head = nullptr;
node *tail = nullptr;
void tambah_awal_list() {
int id;
char name[20];
char gol;

node *baru = new node;
baru->id=head->id;
std::cout << "Id : ";
std::cin >> baru->id;
if (head->id == baru->id){
std::cout << "Id cant be same"<<std::endl;
}

std::cout << "Name : ";
std::cin >> baru->name;
std::cout << "Blood type (A/B/O) : ";
std::cin >> baru->gol;

if(head == nullptr) {
head = baru;
head->next = nullptr;
tail = head;
} else {
baru->next = head;
head = baru;
}
}

我应该改变什么?

这取决于规格和性能要求。

  1. 如果id可以由代码而不是用户输入决定,那么您只需要在每次创建节点时都有一个全局计数器增量。
    在多线程情况下,当节点数超出int范围时,必须小心处理。
// Global variable or class member
int g_nextID = 0;
int generateID(){return ++g_nextID;}
void generate(){
node* n = new node();
n->id = generateID();
// ... 
}
  1. 使用占用0(1)时间和0 (N)空间的std::unordered_set<int>
// A global variable or class member
std::unordered_set<int> g_used;
node *head = nullptr;
node *tail = nullptr;
void generate(){
// Inside the function
int id;
// Get user input into id
// ...
// Checking if used
if(g_used.find(id) == g_used.end()){
// Create the node
// ...
g_used.insert(id); // Save it
}else{
// Error handling.
}
}
void removeNode(int id){
// Remove it from list
// ...
// Remove it from set
g_used.erase(id);
}
  1. 查找节点,但需要O(N)次

最新更新