数据结构线性表插入删除查找的示例

        数据结构书(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!

转载于:https://www.cnblogs.com/cattree/p/7452092.html

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值