VS2019
求大佬解答用单链表实现通讯录遇到的这些问题,急。
若我没将问题没描述清楚,请联系我
头文件:
#pragma once
#include<iostream>
using namespace std;
#include<string>
template<class T>
struct Node {
T data; struct Node<T>* next;
};
template<class T>
class LinkList
{
public:
LinkList(T a[], int n, double h)//头插法构造
{
front = new Node<T>;
front->next = NULL;
for (int i = n - 1; i >= 0; i--)
{
Node<T>* s = new Node<T>;
s->data = a[i];
s->next = front->next;
front->next = s;
}
};
LinkList(T a[], int n, int e)//尾插法构造
{
front = new Node<T>;
Node<T>* r = front;
for (int i = 0; i < n; i++)
{
Node<T>* s = new Node<T>;
s->data = a[i];
r->next = s;
r = s;
}
};
//获取第i个位置上的元素结点的地址yc
Node<T>* Get(int i)
{
Node<T>* p = front->next;
int j = 1;
while (p != NULL && j != i)
{
p = p->next;
j++;
}
return p;
};
int GetLenth()//获取链表的长度yc
{
Node<T>* p = front->next;
int length = 0;
while (p != NULL) {
p = p->next; length++;
}
};
void Insert(int i, T x)//插入
{
Node<T>* p = front;
if (i != 1) p = Get(i - 1);
if (p) {
Node<T>* s = new Node<T>;
s->data = x;
s->next = p->next;
p->next = s;
}
else throw"插入位置错误";
};
T Delete(int i)//删除
{
Node<T>* p = front;
if (i != 1)p = Get(i - 1);
Node<T>* q = p->next;
p->next = q->next;
T x = q->data;
delete q;
return x;
};
/*
Node<T>* Get(int i)//按位置查找
{
Node<T>* p = front->next; int j = 1;
while (p && j != i) {
p = p->next; j++;
}
return p;
};
*/
int Locate(T x)//按值查找
{
Node<T>* p = front->next;
int j = 1;
while (p) {
if (p->data == x)return j;
p = p->next; j++;
}
return -1;
};
~LinkList()//销毁
{
Node<T>* p = front;
while (p) {
front = p; p = p->next; delete front;
}
};
void PrintList()//显示
{
Node<T>* p = front->next;
while (p != NULL)
{
p->data.Print();
p = p->next;
}
cout << endl;
};
private:
Node<T>* front;
};
class PHONE
{
public:
PHONE();
PHONE(int id, string name, string phone, string group) {
x_id = id; x_name = name; x_phone = phone; x_group = group;
};
void Print() {
cout << x_name << " " << x_phone << " " << x_group << endl;
};
bool operator==(PHONE& p)
{
if (p.x_id == x_id)return true; return false;
}
private:
int x_id; string x_name; string x_phone; string x_group;
};
源文件:
#include"tem.h"
int main()
{
PHONE pbook[4] = { {1,"liming","111111","classmates"},{2,"zhangtao","222222","teachers"},{3,"zhoulian","333333","family"},{4,"songxu","444444","classmates"} };
PHONE record{ 5,"wangwu","000000","classmates" };
LinkList<PHONE>list(pbook, 4, 1.111);
cout << "通讯录列表为:" << endl;
list.PrintList();
list.Insert(1, record);
cout << "通讯录列表:" << endl;
list.PrintList();
PHONE x = list.Delete(3);
cout << "删除元素:" << endl; x.Print();
cout << "通讯录列表:" << endl;
list.PrintList();
int w = list.Locate(record);
cout << "插入的元素的位置是:" << w << endl;
}