c语言学习之顺序表操作



//seqlist.h

#ifndef _SEQLIST_H_
#define _SEQLIST_H_

#define MAXSIZE  100

typedef struct
{
    int listLen;  //节点数量
    DATA_T  dataList[MAXSIZE+1];
}seqListType;

/* 初始化顺序表 */
void seqlist_init(seqListType *sl);

/* 返回顺序表的元素数量 */
int seqlist_length(seqListType *sl);

/* 向顺序表中添加元素 */
int seqlist_add(seqListType *sl,DATA data);

/* 向顺序表中插入元素 */
int seqlist_insert(seqListType *sl,int n,DATA data);

/* 向顺序表中删除元素 */
int seqlist_delete(seqListType *sl,int n);

/* 根据序号返回元素 */
DATA *seqlist_find_by_num(seqListType *sl,int n);

/* 按关键字查找 */
int seqlist_find_by_cont(seqListType *sl,int *key);

/* 遍历顺序表中的内容 */
int seqlist_all(seqListType *sl);

#endif



//seqlist.c

#include <stdio.h>


void seqlist_init(seqListType *sl)
{
    sl->listLen = 0;
}

int seqlist_length(seqListType *sl)
{
    return sl->listLen;
}

int seqlist_add(seqListType *sl,DATA data)
{
    if(sl->listLen >= MAXSIZE)
    {
        printf("seqlist is full,can't add!\n");
        return -1;
    }
    else
    {
        sl->dataList[++sl->listLen] = data;
    }
    return 0;
}

int seqlist_insert(seqListType *sl,int n,DATA data)
{
    int i = 0;
    if(sl->listLen >= MAXSIZE)
    {
        printf("seqlist is full,can't insert!\n");
        return -1;
    }

    for(i=sl->listLen;i>=n;i--)
    {
        sl->dataList[i+1] = sl->dataList[i];
    }
    sl->dataList[n] = data;
    sl->listLen++;

    return 0;
}

int seqlist_delete(seqListType *sl,int n)
{
    int i = 0;
   
    if(sl->listLen == 0)
    {
        printf("listLen is null\n");
        return -1;
    }
    if(n>(sl->listLen))
    {
        printf("the element can't find!\n");
        return -1;
    }
    for(i=n;i<(sl->listLen);i++)
    {
        sl->dataList[i] = sl->dataList[i+1];
    }
    sl->listLen--;

    return 0;
}

DATA *seqlist_find_by_num(seqListType *sl,int n)
{
    if((n<1) || (n>(sl->listLen)))
    {
        printf("the element can't find!\n");
        return NULL;
    }
    return &(sl->dataList[n]);
}

int seqlist_find_by_cont(seqListType *sl,char *key)
{
    int i = 0;
    for(i = 1;i<=(sl->listLen);i++)
    {
        if(strcmp(sl->dataList[i].key,key) == 0)
        {
            return i;
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值