头文件:
#pragma once
#pragma once
#include<iostream>
using namespace std;
template<class T>
struct Node {
T data; struct Node<T>* next = NULL;
};
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;
}
};
void Insert(int i, T x)//插入
{
Node<T>* s = new Node<T>;//建立新结点
Node<T>* p = front;
if (i != 1) p = Get(i - 1);
if (p) {
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;
};
//获取第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;
};
/*
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;
};
int GetLenth()//获取链表的长度yc
{
Node<T>* p = front->next;
int length = 0;
while (p != NULL) {
p = p->next; length++;
}
return length;
};
~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 TEXT
{
public:
TEXT(int t) {
x_t = t;
};
void Print() {
cout << x_t << endl;
};
bool operator==(TEXT& p)
{
if (p.x_t == x_t) return true;
return false;
}
private:
int x_t;
};
源文件:
#include"标头.h"
int main() {
TEXT s[5] = { 1,2,3,4,5 };
LinkList<TEXT>list(s, 5, 1.111);//实现头插法
list.Insert(2, 9);//在第二个位置插入数字9
list.Locate(2);//按位查找第二个元素并返回其值
list.GetLenth();//获取线性表的长度
list.~LinkList();//销毁线性表
list.PrintList();//显示
}
实现单链表的一个简单实例,编译出现错误C2280尝试引用已删除的函数