链表
#include <iostream>
using namespace std;
struct MyList
{
int data;
MyList*next;
};
void Init(MyList&head)
{
head.data=0;
head.next=NULL;
}
void ListInsert(MyList&head,int i,int data)
{
int j=1;
MyList*p,*s;
p=&head;
while(p&&j<i)
{
p=p->next;
j++;
}
if(!p||j>i)
{
return;
}
s=new MyList();
s->data=data;
s->next=p->next;
p->next=s;
}
void update(MyList&head,int i,int data)
{
int j=1;
MyList*p=&head;
while(p)
{
p=p->next;
if(j==i)
{
break;
}
j++;
}
if(!p||j>i)
{
return;
}
p->data=data;
}
void del(MyList&head,int i)
{
int j=1;
MyList*p=&head;
MyList*s;
while(p&&j<i)
{
p=p->next;
j++;
}
if(!p||j>i)
{
return;
}
s=p->next;
p->next=s->next;
delete s;
}
int query(MyList&head,int i,int *e)
{
int j=1;
MyList*p=&head;
while(p)
{
p=p->next;
if(j==i)
{
break;
}
j++;
}
if(!p||j>i)
{
return -1;
}
*e=p->data;
return 0;
}
void show(MyList head)
{
MyList* p=head.next;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
int main()
{
MyList head;
Init(head);
for(int i=0;i<10;i++)
{
ListInsert(head,i+1,20+i);
}
cout<<"update"<<endl;
update(head,5,200);
show(head);
del(head,1);
cout<<"delete"<<endl;
show(head);
cout<<"query"<<endl;
int result=0;
query(head,2,&result);
cout<<result<<endl;
cin.get();
}
posted on 2016-08-28 22:51 fendoudexiaoniao 阅读(134) 评论(0) 编辑 收藏 举报