链表的定义以及成员函数的声明

首先定义一个节点类

template <class datatype>//表格类型数据通用模板
class Node{  //定义节点类
public:
    datatype data;
    Node<datatype> *next;
};

 其中含有该节点的数据元素信息以及指向下一个节点的指针,datatype数据模板中包含int 和chr等常见数据类型

接下来定义一个链表类其中用到节点类

class List{
private:
    Node<datatype> *head;//头结点类
public:
    List(){head =NULL;}//构造函数
    int length(); //求表长函数
    bool get_date(int i, datatype &x);//取表中元素
    bool insert_data(datatype data,int i);//从i位置插入元素
    bool delet_dataa(int i);//删除元素
    void prine_List();//打印元素
    ~List(){
    Node<datatype> *p;
    while(head){
        p=head;
        head=head->next;
        delete p;
        }
    };

};

其中private中定义了每条链表中的头结点信息,形成封装的概念,该链表只能同过public中函数访问head节点来访问链表中的每个元素

接下来是有关于成员函数的定义,主要和每个人的算法实现有关,这里不做详细介绍

template <class datatype>
int List<datatype>::length(){
    int i=0;
    Node<datatype> *current=head;
while(current)
    {
     i++;
      current=current->next;
    }
    return i;
}
template <class datatype>
bool List<datatype>::get_date(int i,datatype &b ){

    int j,x;
    if(i<1||i>length()+1)
    {
        cout<<"can't find posation of message"<<endl;
    return false;}
    for(j=1;j<i;j++){
        x=head->data;
        head=head->next;
    }
    cout<<x<<endl;
    return true;
}
template <class datatype>
bool List<datatype>::insert_data(datatype data,int i){
 Node<datatype> *current, *previous ,*newnode;
  int j=1;
if ((i>length()+1)||(i<0))
    {
        cout<<"this is a error posation"<<endl;
        return false;
    }
    newnode=new Node<datatype>;
    if(newnode==NULL)
    {
        cout<<"don't have posation to storage it "<<endl;

    }
    newnode->data=data;
    newnode->next=NULL;
    if(i==1){
        newnode->next=head;
        head=newnode;
        return true;
    }
    current=previous=head;
    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>::prine_List()
{
    Node<datatype> *current;
    current=head;
    while(current){
        cout<<current->data<<" ";
        current=current->next;
    }
    cout<<endl;
}

主函数测试

int main()
{
    List<int> fist_list;
    int i;
    for(i=1;i<5;i++)
    {
        fist_list.insert_data(i*100,1);
    }
    cout<<"ouput_data:\n";
    fist_list.prine_List();
    fist_list.~List();
    return 0;

 

转载于:https://www.cnblogs.com/xxxxbai/p/7604076.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值