一、学习要点:
1.模板函数、模板类的应用;
2.尾节点的指针内容为空,有利于计算链表长度,和插入和删除节点是否越界;
3.加深对成员变量应用的认识.
二、程序运行代码:
#include<stdlib.h>
#include<iostream>
using namespace std;
template<class DataType>
struct Node{
DataType data;
struct Node<DataType> *next;
};
template<class DataType>
class LinkList{
public:
LinkList();
LinkList(DataType array[],int n);
LinkList(int n,DataType array[]);
~LinkList();
int GetLength();
int GetLocal(DataType x);
DataType GetElement(int index);
void Insert(int index,DataType x);
DataType Delete(int index);
void PrintLinkedList();
private:
Node<DataType>*first;
};
template<class DataType>
LinkList<DataType>::LinkList(){
first=new Node<DataType>;
first->next=NULL;
}
template<class DataType>
LinkList<DataType>::LinkList(DataType array[],int n){
first=new Node<DataType>;
Node<DataType> *p=first;
for(int i=0;i<n;i++){
Node<DataType> *temp=new Node<DataType>;
temp->data=array[i];
temp->next=p->next;
p->next=temp;
p=p->next;
}
p->next=NULL;
}
template<class DataType>
LinkList<DataType>::LinkList(int n,DataType array[]){
Node<DataType> temp=new Node<DataType>;
for(int i=0;i<n;i++){
temp->data=array[i];
temp->next=first->next;
first->next=temp;
}
}
template<class DataType>
LinkList<DataType>::~LinkList(){
Node<DataType> *p;
p=first->next;
while(p!=NULL){
Node<DataType> *temp;
temp=p;
p=p->next;
delete temp;
}
}
template<class DataType>
void LinkList<DataType>::Insert(int index,DataType x){
Node<DataType> *p=first->next;
int count=0;
while(p!=NULL&&count<index-1){
p=p->next;
count++;
}
if(p==NULL){
throw"插入有误";
}else{
Node<DataType> *temp=new Node<DataType>;
temp->data=x;
temp->next=p->next;
p->next=temp;
}
}
template<class DataType>
int LinkList<DataType>::GetLocal(DataType x){
Node<DataType> *p=first->next;
int count=1;
while(p!=NULL){
if(p->data=x){
return count;
}
p=p->next;
count++;
}
return 0;
}
template<class DataType>
DataType LinkList<DataType>::GetElement(int index){
Node<DataType> *p=first->next;
int count=1;
while(p!=NULL&&count<index){
p=p->next;
count++;
}
if(p==NULL){
throw"error position"
}else{
return p->data;
}
}
template<class DataType>
int LinkList<DataType>::GetLength(){
Node<DataType> *p=first->next;
int count=0;
while(p!=NULL){
count++;
p=p->next;
}
return count;
}
template<class DataType>
void LinkList<DataType>::PrintLinkedList(){
Node<DataType> *p;
p=first->next;
while(p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
}
int main(){
int array[]={1,3,5,2,7,6,9,8,10,4};
LinkList<int> LinkedList=LinkList<int>(array,10);
LinkedList.PrintLinkedList();
system("pause");
return 0;
}
三、程序运行结果: