#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;
}