數據結構 單鏈表 (C++)

#include
using namespace std;


template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T> 
class SingleList
{
public:
SingleList()
{
first=new Node<T>;
first->next=NULL;
length = 0;
}
SingleList(T a[],int ListLength,int MaxSize);
~SingleList();
int Length();
T Get(int i);
   int  Find(T x);
bool Insert(int i,T x);
T Delete(int i);
void PrintList();
    private:
Node<T> *first;
int length;
};
//查找鏈表中的第i個元素並返回其值,i從1開始
template<class T>
T SingleList<T>::Get(int i)
{
if(i>length)
{
cout<<"position error!"<<endl;
return false;
}
else
{
Node<T> *p=first->next;
int j=1;
while(j<i)
{
p=p->next;
j++;
}
return p->data;
}
}
//在鏈表中的第i個元素之前插入一個值爲x的結點,i從1開始,i=length+1爲在最後一個結點之後插入
template<class T>
bool SingleList<T>::Insert(int i,T x)
{
if(i>(length+1)||i<=0)
{
cout<<"position error!"<<endl;
return false;
}
else
{
Node<T> *p=first;
int j=1;
while(j<i)
{
p=p->next;
j++;
}
Node<T> *s=new Node<T>;
s->data=x;
s->next=p->next;
p->next=s;
length++;
return true;


}
}
//刪除鏈表中的第i個元素,i從1開始
template<class T>
T SingleList<T>::Delete(int i)
{
if(i>length||i<=0)
{
cout<<"position error!"<<endl;
return false;
}
else
{
Node<T> *p = first;
int j = 1;
while(j<i)
{
p = p->next;
j++;
}
Node<T> *q = p->next;
T x = q->data;
p->next = q ->next;
delete q;
length--;
return x;
}
}






//鏈表帶初始化的構造函數
template<class T>
SingleList<T>::SingleList(T a[],int ListLength,int MaxSize)
{
first = new Node<T>;
first->next=NULL;
if(ListLength>MaxSize)
{
cout<<"error"<<endl;
return ;
}
for(int i = 0;i<ListLength;i++)
{
Node<T> *s = new Node<T>;
s->data = a[i];
s->next = first->next;
first->next = s;
}
length = ListLength;


}
template<class T>
SingleList<T>::~SingleList( )
{
Node<T> *p = first;
while(p)
{
Node<T> *q=p;
p=p->next;
delete q;
}
}
template<class T>
void SingleList<T>::PrintList( )
{
Node<T> *p = first->next;
while(p)
{
cout<<p->data<<endl;
p = p->next;
}
}
template<class T>
int  SingleList<T>::Length()
{
return length;
}
//查找鏈表中數據值爲x的元素在鏈表中的位置
template<class T>
int  SingleList<T>::Find(T x)
{
Node<T>* p =first->next;
int i = 1;
while(p)
{
if(p->data==x)
return i;
else
{
p = p->next;
i++;
}
}
cout<<"Does not exist!"<<endl;
return -1;
}


void main()
{
int a[5]={1,2,3,4,7};
//cout<<sizeof(a)<<endl;
SingleList<int> AList(a,5,sizeof(a)/sizeof(int));
AList.PrintList();
AList.Delete(3);
cout<<"After Delette"<<endl;
AList.PrintList();
AList.Insert(5,21);
cout<<"After Insert: "<<endl;
AList.PrintList();
cout<<"Get: "<<AList.Get(2)<<endl;
cout<<"Length: "<<AList.Length()<<endl;
cout<<"Find77: "<<AList.Find(77)<<endl;
cout<<"Find7: "<<AList.Find(7)<<endl;
system("pause");


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章