零个或多个数据元素的有效限序列
首先它是一个序列,元素之间是有序的,若元素存在多个,则第一个元素无前驱,最后一个元素无后继,其他元素有且只有一个前驱和后继
头文件
#ifndef _SEQUENCELIST_H
#define _SEQUENCELIST_H //自定义库函数
#define SIZE 10 //宏定义
#define SUCCESS 10000
#define FAILURE 10001
typedef int ElemType; //为int数据类型定义新名字
struct SequenceList //结构体
{
int length;
ElemType *data;
}; // ;不可丢
typedef struct SequenceList SeList;
int SequenceInit(SeList *l);
int SequenceInsrt(SeList *l, int p, ElemType e);
#endif
自定义函数
#include <stdio.h>
#include <stdlib.h>
#include "SequenceList.h" //头文件中自定义的库函数
int SequenceInit(SeList *l) //传过来的是地址,接收要用指针
{
if(NULL == l) //入参判断
{
return FAILURE;
}
l->length = 0; //长度初始值为0
return SUCCESS;
}
int SequenceInsrt(SeList *l, int p, ElemType e)
{
int i;
if(NULL == l)
{
return FAILURE;
}
if(p > l->length + 1 || l->length >= SIZE || p < 1) //p有意义的条件
{
return FAILURE;
}
for(i = 0; i < l->length - p + 1; i++) //从插入的地方依次向后移实现插入
{
l->data[l->length - i] = l->data[l->length - i - 1];
}
l->data[p - 1] = e;
l->length++; //插入一个元素后,结构体的长度发生了变化
return SUCCESS;
}
主函数
#include <stdio.h>
#include <stdlib.h>
#include "SequenceList.h"
#include <time.h>
int main()
{
int i, ret;
SeList list;
srand(time(NULL));
ret = SequenceInit(&list); //要改变list里元素的值,所以要传地址
if(ret == SUCCESS)
{
printf("Init Success!\n");
}
else
{
printf("Init Failure!\n");
}
for(i = 0; i < 5; i++)
{
ret = SequenceInsrt(&list, i + 1, rand() % 10);
if(FAILURE == ret)
{
printf("Insert Failure!\n");
}
else
{
printf("Insert Success!\n");
}
}
return 0;
}