顺序表:采用顺序存储方式的线性表称为顺序表数组
顺序存储结构:指的是用一段地址连续的存储单元依次存储线性表的数据元素,因为是依次存放的,所以只要知道顺序表的首地址及数据元素所占的存储长度,就容易计算出任何一个元素的位置code
(1)定义顺序表的结构string
#include <stdio.h> #include <string.h> #define MAXSIZE 100 //定义顺序表最大长度 typedef struct { //定义数据类型 char key[15]; char name[20]; int age; } DATA; typedef struct { DATA ListData[MAXSIZE+1]; //保存顺序表数组 int ListLen; //顺序表已存节点的数量 } SeqListType;
(2)定义顺序表操做it
void SeqListInit(SeqListType *SL); //初始化顺序表 int SeqListLength(SeqListType *SL); //返回顺序表的元素数量 int SeqListAdd(SeqListType *SL, DATA data); //向顺序表中添加元素 int SeqListInsert(SeqListType *SL, int n, DATA data); //向顺序表中插入元素 int SeqListDelete(SeqListType *SL, int n); //删除顺序表中的数据元素 DATA *SeqListFindByNum(SeqListType *SL, int n); //根据序号返回元素 int SeqListFindByKey(SeqListType *SL, char *key); //按关键字查找 int SeqListAll(SeqListType *SL); //遍历顺序表的内容
(3)顺序表操做io
/* *初始化顺序表 * */ void SeqListInit(SeqListType *SL) { SL->ListLen = 0; //设置顺序表长度为0 } /* *返回顺序表的元素数量 * */ int SeqListLength(SeqListType *SL) { return (SL->ListLen); } /* *向顺序表中添加元素 * */ int SeqListAdd(SeqListType *SL, DATA data) { if (SL->ListLen >= MAXSIZE) { printf("顺序表已满,不能再添加节点!\n"); return 0; } SL->ListData[++SL->ListLen] = data; return 1; } /* *向顺序表中插入元素 * */ int SeqListInsert(SeqListType *SL, int n, DATA data) { int i; if (SL->ListLen >= MAXSIZE) { printf("顺序表已满,不能再添加节点!\n"); return 0; } if (n<1 || n>SL->ListLen-1) { printf("插入节点序号错误,不能插入元素!\n"); return 0; } for (i=SL->ListLen; i>=n; i--) { SL->ListData[i+1] = SL->ListData[i]; } SL->ListData[n] = data; SL->ListLen++; return 1; } /* *删除顺序表中的数据元素 * */ int SeqListDelete(SeqListType *SL, int n) { int i; if (n<1 || n>SL->ListLen+1) { printf("删除节点序号错误,不能删除节点!\n"); return 0; } for (i=n; i<SL->ListLen; i++) { SL->ListData[i] = SL->ListData[i+1]; } SL->ListLen--; return 1; } /* *根据序号返回元素 * */ DATA *SeqListFindByNum(SeqListType *SL, int n) { if (n<1 || n>SL->ListLen+1) { printf("节点序号错误,不能返回节点!\n"); return NULL; } return &(SL->ListData[n]); } /* *按关键字查找 * */ int SeqListFindByKey(SeqListType *SL, char *key) { int i; for (i=1; i<=SL->ListLen; i++) { if (strcmp(SL->ListData[i].key, key) == 0) return i; } return 0; } /* *遍历顺序表的内容 * */ int SeqListAll(SeqListType *SL) { int i; for (i=1; i<=SL->ListLen; i++) { printf("(%s,%s,%d)\n", SL->ListData[i].key, SL->ListData[i].name, SL->ListData[i].age); } }