#include "stdafx.h"
#include<iostream>
using namespace std;
template<class T>
struct Node //定义结构体
{
T data;
Node<T> *next;
};
template<class T>//定义模板类
class Linklist
{
public:
Linklist();//无参构造函数
Linklist(T a[], int i);//有参构造函数,i是数组长度
~Linklist();
int Length();//求单链表长度
T Get(int i);//获取单链表中第i个位置的元素
int Locate(T x);//获取元素为x的位置
void Insert(T x, int i);//在第i个位置插入元素x
T Delete(int i);//删除位置为i的元素
void Printline();//遍历函数
private:
Node<T> *first=new Node<T>;//定义头指针
};
//方法在类外的实现
template<class T>
Linklist<T>::Linklist() {
first = new Node;
first->next = null;
}
template< class T>
Linklist<T>::Linklist(T a[],int i) {
Node<T> *p=new Node<T>;
p = first;
for (int j=0; j < i; j++) {
Node<T> *s = new Node<T>;
s->data = a[j];
p->next = s;
p = s;
}
p->next = NULL;
}
template<class T>
Linklist<T>::~Linklist() {
while (first != NULL)
{
Node<T> *p;
p = new Node<T>;
p = first;
first = first->next;
delete p;
}
}
template<class T>
int Linklist<T>::Length()
{
Node<T> *p;
p = new Node<T>;
p = first->next;
int count = 0;
while (p!=null)
{
p = p->next;
count++;
}
return count;
}
template<class T>
T Linklist<T>::Get(int i)
{
Node<T> *p;
p = new Node<T>;
p = first->next;
int count = 1;
while (p != NULL && count < i)
{
p = p->next;
count++;
}
if (p == NULL) throw "位置";
else return p->data;
}
template<class T>
int Linklist<T>::Locate(T x)
{
Node<T> *p=new Node<T>;
p = first->next;
int count = 1;
while (p != NULL)
{
if (p->data == x) return count;
p = p->next;
count++;
}
return 0;
}
template<class T>
void Linklist<T>::Insert(T x, int i)
{
Node<T> *p;
p = new Node<T>;
p = first;
int count = 0;
while (p != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL)throw"位置";
else {
Node<T> *s;
s = new Node;
s->data = x;
s->next = p->next;
p->next = s;
}
}
template<class T>
T Linklist<T>::Delete(int i)
{
Node<T> *p=new Node<T>;
p = first;
int count = 0;
while (p != NULL && count < i - 1)
{
p = p->next;
count++;
}
if (p == NULL || p->next == NULL) throw"位置";
else {
Node<T> *q;
q = new Node<T>;
q = p->next; T x = q->data;
p->next = q->next;
delete q;
return x;
}
}
template<class T>
void Linklist<T>::Printline()
{
Node<T> *p=new Node<T>;
p = first->next;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
cout << endl;
}
int main()
{
int a[5] = {1,2,3,4,5};
Linklist<int> m = Linklist<int>(a, 5);
m.Printline();
cout<<m.Get(2)<<endl;
cout<<m.Locate(3)<<endl;
m.Delete(2);
m.Printline();
return 0;
}