64,654
社区成员
发帖
与我相关
我的任务
分享
template <class datatype>
class NODE
{
public:
datatype data;
NODE<datatype> *next;
};
template<class datatype>
class LIST
{
private:
NODE<datatype> *head;
public:
LIST(){
// head=new NODE<datatype>; // 将head赋空值
// head->next=NULL;
head = NULL;
};
bool get_data(int i,datatype &x);
bool insert_data(int i,datatype data);
bool delete_data(int i);
void print_list();
int get_num(int x);
~LIST()
{
NODE<datatype> *p;
while(head)
{
p=head;
head=head->next;
delete p;
}
}
};
template<class datatype>
int LIST<datatype>::get_num(int x)
{
NODE<datatype> *current;
int j=1;
current=head;
while((current->data!=x) && j<=6)
{
j++;
current=current->next;
}
return j;
}
template<class datatype>
bool LIST<datatype>::delete_data(int i)
{
NODE<datatype> *current,*previous;
int j=1;
if(head==NULL)
{
cout<<"表已空,不能删除。\n";
return false;
};
if((i<1)||(i>6))
{
cout<<"删除位置不正确,不能删除!\n";
return false;
}
current=previous=head;
while(current&&j<i)
{
previous=current;
current=current->next;
j++;
};
if(head==current)
{
head=head->next;
delete current;
}
else
{
previous->next=current->next;
delete current;
}
return true;
}
template<class datatype>
bool LIST<datatype>::get_data(int i,datatype &x)
{
NODE<datatype> *current;
int j=1;
if((i<1)||(i>6))
{
cout<<"非法位置读取元素,不能读取!\n";
return false;
}
current=head;
while(current!=NULL&&j<i)
{
j++;
current=current->next;
}
x=current->data;
return true;
}
template<class datatype>
bool LIST<datatype>::insert_data(int i,datatype data)
{
NODE<datatype> *current,*previous,*newnode;
int j=1;
if((i>7) || (i<0))
{
cout<<"插入位置不正确,不能插入!\n";
return false;
}
newnode=new NODE<datatype>;
if(newnode==NULL)
{
cout<<"内在无空间,表已满,不能插入!\n";
return false;
}
newnode->data=data;
newnode->next=NULL;
// previous=head; // 下面的逻辑有点问题,按照这样改
if (head == NULL)
{
head=newnode;
return true;
}
current=head/*->next*/;
while(current!=NULL&&j<i)
{
previous=current;
current=current->next;
j++;
}/*;*/
newnode->next=current;
previous->next=newnode;
return true;
}
template<class datatype>
void LIST<datatype>::print_list()
{
NODE<datatype> *current;
current=head;
while(current)
{
cout<<current->data<<" ";
current=current->next;
}
cout<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i,n,x;
int arry[6]={21,23,25,27,29,31};
LIST<int>list;
for(i=1;i<=6;i++)
list.insert_data(i,arry[i-1]);
cout<<"该链表为:";
list.print_list();
cout<<endl;
cout<<"输入序号:";
cin>>n;
int i_data=100;
list.get_data(n,i_data);
cout<<"输出值为:"<<i_data<<endl;
cout<<"输入值:";
cin>>x;
cout<<"输出序号:"<<list.get_num(x)<<endl;
cout<<"插入结点:";
cin>>n>>x;
list.insert_data(n,x);
cout<<"输出链表:";
list.print_list();
cout<<endl;
cout<<"删除结点:";
cin>>n;
list.delete_data(n);
cout<<"输出链表:";
list.print_list();
cout<<endl;
return 0;
}