C语言实现顺序表的插入、删除、查找、遍历等基本操作
/*编写完整的程序实现顺序的建立、查找、插入、删除等基本操作*/
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int EleType;
/*定义顺序表类型定义*/
typedef struct SqList{
EleType *elem;
int length ; //当前链表的长度
int listsize; //当前链表分配的存储容量
}SqList; //顺序表类型
/*构造一个空的线性表L*/
int InitList_Sq(SqList *L)
{
L->elem=(EleType *)malloc(sizeof(EleType));
if(! L->elem) exit(OVERFLOW); //存储空间分配失败
L->length=0; //空表的长度为0
L->listsize=LIST_INIT_SIZE; //分配给空表的存储容量
return OK;
}
/*返回线性表L第i个位置的数据*/
EleType GetElem_Sq(SqList L,int i)
{
//检查i的合法性
if(i<1 || i>L.length) return ERROR; //i非法
return L.elem[i-1];
}
/*查找线性表中第一个与所给数据匹配的数据元素的位置*/
int LocateElem( SqList L, EleType e)
{
int i=1;
EleType *p=L.elem;
while(*p != e && i<=L.length) {i++;p++;} //p指向下一个元素