(C++)线性表的链式存储

#include<iostream>
using namespace std;
typedef int datatype;
struct node{
    datatype data;
    node *next;
};
class list{
    public:
        list();
        int length()const;
        //~list();
        datatype get_num(int i);
        node* locate(const datatype x)const;
         void insert(const int i,const datatype x);
        void delete_num(const int i);
         node* get_head()   {return head;}
    private:
        int count;
        node* head;              //带头结点的链式线性表 
};

list::list(){
    head=new node;
    head->next=NULL;
    count=0;
}

int list::length()const
{
    return count;
}

datatype list::get_num(int i)
{
    node* p=head->next;  int j=1;
    while(p!=NULL&&j!=i)
    {
        p=p->next;  j++;   
    }
    if(p==NULL)  cout<<"Range Error...\n";           //==之前写成=,坑死我了 
    return p->data;
}

node* list::locate(const datatype x)const
{
    node *p=head->next;
    while(p!=NULL)
    {
        if(p->data==x) return p;
        else p=p->next;
    }
    return NULL;             
}

void list::insert(const int i,const datatype x)
{
    if(i<1||i>count+1)  cout<<"Range Error...\n";
    node *p=head;  int j=0;
    while(j!=i-1&&p!=NULL)        //搜索前一个节点 
    {
        p=p->next; j++;
    }
    node *s=new node;
    s->data=x;
    s->next=p->next;
    p->next=s;
    count++;
}

void list::delete_num(const int i)
{
    node *p=head;  int j=0;
    while(j!=i-1&&p!=NULL)
    {
        p=p->next; j++;
    }
    if(i<1||i>count)  cout<<"Range Error...\n";
    node *u=p->next;
    p->next=u->next;
    delete u;
    count--;
}

//测试 
main()
{
    list l;
    l.insert(1,1);
    cout<<l.length()<<endl;
    l.insert(2,2);
    l.insert(3,3);
    l.insert(4,4);
    l.insert(5,5);
    cout<<l.locate(3)<<endl;
    l.delete_num(5) ;
    cout<<l.get_num(4)<<endl;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值