class Emp
{
public:
Emp(int id, string name)
{
this->id = id;
this->name = name;
}
int id;
string name;
Emp *next=nullptr;
};
class EmpLinkedList
{
public:
EmpLinkedList(){}
void add(Emp *emp)
{
if (head == nullptr)
{
head = emp;
return;
}
Emp * temp = head;
while (true)
{
if (temp->next == nullptr)
{
break;
}
temp = temp->next;
}
temp->next = emp;
}
void list(int no)
{
if (head == nullptr)
{
cout << "第"<<no+1<<"链表为空" << endl;
return;
}
cout << "第" << no + 1 << "链表的内容为:" ;
Emp *temp = head;
while (true)
{
if (temp != nullptr)
{
cout << "id:" << temp->id << " name:" << temp->name << endl;
}
else
{
break;
}
temp = temp->next;
}
}
Emp* findById(int id)
{
if (head == nullptr)
{
cout << "链表为空" << endl;
return nullptr;
}
Emp *temp = head;
bool flag = false;
while (true)
{
if (temp->id == id)
{
flag = true;
break;
}
if (temp->next == nullptr)
{
break;
}
temp = temp->next;
}
if (flag == true)
{
return temp;
}
else
{
return nullptr;
}
}
void DeleteById(int id)
{
if (head == nullptr)
{
cout << "链表为空,无法删除元素" << endl;
return;
}
Emp *temp = head;
bool headflag = false;
bool flag = false;
while (true)
{
if (head->id == id)
{
headflag = true;
break;
}
if (temp->next == nullptr)
{
break;
}
if (temp->next->id == id)
{
flag = true;
break;
}
temp = temp->next;
}
if (headflag == true)
{
head = nullptr;
}
else
{
if (flag == true)
{
if (temp->next->next == nullptr)
{
temp->next = nullptr;
}
else
{
temp->next = temp->next->next;
}
}
else
{
cout << "未找到要删除的元素" << endl;
}
}
}
void UpdataById(Emp *newEmp)
{
Emp *temp = findById(newEmp->id);
if (temp)
{
temp->name = newEmp->name;
}
else
{
cout << "未找到要更改的员工" << endl;
}
}
private:
Emp *head = nullptr;
};
class HashTable
{
public:
HashTable(int size)
{
this->size = size;
emplinkedlistArr = new EmpLinkedList[size];
}
void add(Emp *emp)
{
int emplinkedlistNO = HashFun(emp->id);
emplinkedlistArr[emplinkedlistNO].add(emp);
}
void list()
{
for (int i = 0; i < size; i++)
{
emplinkedlistArr[i].list(i);
}
}
void findById(int id)
{
int emplinkedlistNO = HashFun(id);
Emp *emp = emplinkedlistArr[emplinkedlistNO].findById(id);
if (emp)
{
cout << "在第" << emplinkedlistNO + 1 << "条链表找到id" << endl;
cout << "id:" << emp->id << "name:" << emp->name << endl;
}
else
{
cout << "没有找到" << endl;
}
}
void DelById(int id)
{
int emplinkedlistNO = HashFun(id);
emplinkedlistArr[emplinkedlistNO].DeleteById(id);
}
void UpDataById(Emp *newEmp)
{
int emplinkedlistNO = HashFun(newEmp->id);
emplinkedlistArr[emplinkedlistNO].UpdataById(newEmp);
}
int HashFun(int id)
{
return id % size;
}
private:
EmpLinkedList *emplinkedlistArr;
int size;//表示共有多少条链表
};
int main()
{
HashTable hash(7);
Emp *emp = new Emp(2,"liuliu");
hash.add(emp);
hash.list();
Emp *emp1 = new Emp(1,"uu");
hash.add(emp1);
hash.list();
hash.findById(2);
Emp *newemp = new Emp(1, "mm");
hash.UpDataById(newemp);
hash.DelById(2);
hash.list();
system("pause");
return 0;
}