C语言实现线性表(顺序存储结构)
linearTable.h
#pragma once
//线性表的实现
#define MAXSIZE 20
#define OK -1
#define ERROR -2
typedef struct list {
int data[MAXSIZE]; //数组存储
int len; //线性表长度
}LIST_T;
//线性表初始化
void initList(LIST_T *list);
//根据下表查询数据
int getElem(LIST_T *list, int i);
//根据数据查找下标
int getId(LIST_T *list, int e);
//获取线性表长度
int getLen(LIST_T *list);
//头插法
int addToHead(LIST_T *list, int e);
//尾插法
int addToTail(LIST_T *list, int e);
//指定位置插入
int addSpecific(LIST_T* list, int i, int e);
//删除指定下标元素
int delElembyId(LIST_T *list, int i);
//删除指定元素
int delElem(LIST_T *list, int e);
//清空线性表
void clearList(LIST_T *list);
//打印信息
void show(LIST_T *list);
linearTable.c
#include "linearTable.h"
#include <stdio.h>
//线性表初始化
void initList(LIST_T* list)
{
for (int i = 0; i < MAXSIZE; ++i)
{
list->data[i] = 0;
}
list->len = 0;
}
//根据下表查询数据
int getElem(LIST_T* list, int i)
{
if (i<0 || i>MAXSIZE || i > list->len)
{
return ERROR;
}
return list->data[i];
}
//根据数据查找下标
int getId(LIST_T* list, int e)
{
for (int i = 0; i < list->len; ++i)
{
if (e == list->data[i])
{
return i;
}
}
return ERROR;
}
//获取线性表长度
int getLen(LIST_T* list)
{
return list->len;
}
//头插法
int addToHead(LIST_T* list, int e)
{
if (list->len < MAXSIZE)
{
for (int i = list->len; i >=0; --i)
{
list->data[i] = list->data[i-1];
}
list->data[0] = e;
list->len += 1;
return OK;
}
return ERROR;
}
//尾插法
int addToTail(LIST_T* list, int e)
{
if (list->len < MAXSIZE)
{
list->data[list->len] = e;
list->len += 1;
return OK;
}
return ERROR;
}
//指定位置插入
int addSpecific(LIST_T* list, int i, int e)
{
if (i<0 || i>MAXSIZE || i > list->len)
{
return ERROR;
}
for (int count = list->len; count >= i; --count)
{
list->data[count] = list->data[count - 1];
}
list->data[i] = e;
++list->len;
return OK;
}
//删除指定下标元素
int delElembyId(LIST_T* list, int i)
{
if (i<0 || i>MAXSIZE || i > list->len)
{
return ERROR;
}
for (int count = i; count < list->len; ++count)
{
list->data[count-1] = list->data[count];
}
--list->len;
return OK;
}
//删除指定元素
int delElem(LIST_T* list, int e)
{
for (int count = 0; count < list->len; ++count)
{
if (list->data[count] == e)
{
for (int i = count; i < list->len; ++i)
{
list->data[i] = list->data[i+1];
}
--list->len;
break;
}
}
return OK;
}
//清空线性表
void clearList(LIST_T* list)
{
for (int i = 0; i < list->len; ++i)
{
list->data[i] = 0;
}
list->len = 0;
return OK;
}
//打印信息
void show(LIST_T* list)
{
for (int i = 0; i < list->len; ++i)
{
printf("NO%d:%d\n",i,list->data[i]);
}
printf("\n");
}