#include<iostream>
using namespace std;
template<class DataType>
struct Node
{
DataType data;
Node<DataType> *next;
};
template<class DataType>
class List
{
public:
List();
List(DataType a[], int n);
~List();
int Length();
int Locate(DataType x);
void insert(int i, DataType x);
int Delete(int i);
void PrintList();
private:
Node<DataType> *first;
};
template<class DataType>
List<DataType>::List()
{
first = NULL;
}
template<class DataType>
List <DataType>::List(DataType a[], int n)
{
int i;
Node<DataType> *p, *tail;
tail = NULL;
first = NULL;
for (i = 0; i < n; i++)
{
p = new Node<DataType>;
p->data = a[i];
p->next = NULL;
if (first== NULL)
first= p;
else
tail->next = p;
tail = p;
}
}
template<class DataType>
List<DataType>::~List()
{
Node<DataType>*q;
while (first != NULL)
{
q = first;
first = first->next;
delete q;
}
}
template<class DataType>
int List<DataType>::Length()
{
int count;
Node<DataType>*p;
p = first; count = 0;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
template<class DataType>
int List<DataType>::Locate(DataType x)
{
int count = 1;
Node<DataType>*p;
p = first->next;
while (p != NULL)
{
if (p->next->data== x)return count;
p = p->next;
count++;
}
return 0;
}
template<class DataType>
void List<DataType>::insert(int i, DataType x)
{
Node<DataType>*p, *s;
p = first; int count = 0;
while (p->next != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL)throw"位置";
else {
s = new Node<DataType>; s->data = x;
s->next = p->next;
p->next = s;
}
}
template<class DataType>
int List<DataType>::Delete(int i)
{
int x;
Node<DataType> *q, *p;
p = first;
int count = 0;
while (p->next != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL && p->next == NULL)throw"位置";
else {
q = p->next; x = q->data;
p->next=(p->next)->next;
delete q;
return x;
}
}
template<class DataType>
void List<DataType>::PrintList()
{
Node<DataType> *p;
p = first;
while (p != NULL)
{
cout << p->data<<" ";
p = p->next;
}
cout << endl;
}
int main()
{
int a[20];
int n,x;
cout << "请输入您希望建立的线性表长度:";
cin >> n;
cout << "请依次输入线性表中的各个元素:" << endl;
for (int i = 0; i < n; i++)
cout << "_ ";
for (int i = 0; i < n; i++)
cout << "\b\b";
for (int i = 0; i < n; i++)
cin >> a[i];
List<int> list(a, n);
list.PrintList();
cout << "线性表的长度是:" << endl;
cout << list.Length() << endl;
cout << "下一步,系统希望您知道您想删除的数字,请在横线上输入此位置:" << endl;
cout << "_\b";
cin >> x;
list.Delete(x-1);
cout << "删除成功了!" << endl;
list.PrintList();
cout << "测试的最后一步了!加油!" << endl<<endl;
cout << "系统希望您能输入两个数字来代表在线性表的某个位置插入元素" << endl;
cout << "请在第一个横线处插入你要输入的数据位置,在第二个横线上输入数据" << endl << "_ _\b\b\b";
int i, y;
cin >> i >> y;
list.insert(i-1, y);
list.PrintList();
/*int n, a[10] = {1,2,3,4,5,6,7,8,9,10}, x, y, i;
List<int>List(a, 10);
List.PrintList();
cout << List.Length() << endl;
cin >> x;
List.Delete(List.Locate(x));
List.PrintList();
cin >> y; cin >> i;
List.insert(i, y);
List.PrintList();*/
}
单链表(1)
最新推荐文章于 2022-04-28 07:27:50 发布