数据结构线性表插入删除查找的示例
数据结构书(c语言版)按书敲的不定期更新。
数据结构线性表插入删除查找的示例:
代码:
#include<iostream>
#include<cstdio>
using namespace std;
#define list_init_size 100//空间域
#define listincrememt 10//增加额度
typedef struct
{
int *elem;
int length;
int listsize;
}sqlist;
int initlist_sq(sqlist &l)//建立空表
{
l.elem=(int *)malloc(list_init_size *sizeof(int));
if(!l.elem)
return 0;
l.length=0;
l.listsize=list_init_size;
return 1;
}
int listinsert_sq(sqlist &l,int i,int e)//插入函数
{
if(i<1||i>l.length+1)
return 0;
if(l.length>=l.listsize)
{
int *newbase=(int *)realloc(l.elem,(l.listsize+listincrememt)*sizeof(int));
if(!newbase)
return 0;
l.elem=newbase;
l.listsize+=listincrememt;
}
int *q=&(l.elem[i-1]);
for(int *p=&(l.elem[l.length-1]);p>=q;--p)
*(p+1)=*p;
*q=e;
++l.length;
return 1;
}
int listdelete_sq(sqlist &l,int i,int &e)//删除函数
{
if(i<1||i>l.length)
return 0;
int *p=&(l.elem[i-1]);
e=*p;
int *q=l.elem+l.length-1;
for(++p;p<=q;++p)
{
*(p-1)=*p;
}
--l.length;
return 1;
}
int compare(int a,int b)//查找函数附属函数
{
if (a==b)
return 1;
else
return 0;
}
int locateelem_sq(sqlist l,int e,int(*compare)(int,int))//查找函数
{
int i=1;
int *p=l.elem;
while(i<l.length&&!(*compare)(*p++,e))
++i;
if(i<=l.length)
return i;
else
return 0;
}
int display(sqlist l)//显示函数
{
for(int k=0;k<l.length;k++)
cout<<l.elem[k]<<"\t";
cout<<endl;
return 0;
}
int main()
{
sqlist l;
initlist_sq(l);
cout<<"Please enter the length of the linear table:";
cin>>l.length;
for(int i=0;i<l.length;i++)
{
cin>>l.elem[i];
}
display(l);
int place;
cout<<"Please enter the number of positions to insert:";
cin>>place;
int num;
cout<<"Please enter the number to be inserted:";
cin>>num;
listinsert_sq(l,place,num);
display(l);
int place1;
cout<<"Please enter the location where the number will be deleted:";
cin>>place1;
int num1;
cout<<"Please enter the number to be deleted:";
cin>>num1;
listdelete_sq(l,place1,num1);
display(l);
int num2;
cout<<"Please enter the number to find:";
cin>>num2;
if(locateelem_sq(l,num2,(*compare)))//调用格式!
printf("%d\n",locateelem_sq(l,num2,(*compare)));
return 0;
}
今天也是元气满满的一天,good luck!
我想要变得高一点,最好能伸手给你一片天。