完整代码+2个测试函数
目录
SeqList.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
//定义结构体SeqList
typedef struct
{
DataType list[MaxSize];
int size;
}SeqList;
//初始化
void ListInitiate(SeqList* L);
//求当前数据元素个数
int ListLength(SeqList* L);
//插入数据元素
int ListInsert(SeqList* L, int i, DateType x);
//删除数据元素
int ListDelete(SeqList* L ,int i,DataType* x);
//取数据元素
int ListGet(SeqList* L, int i, DataType* x);
SeqList.c
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef int DateType;
#include"SeqList.h"
//初始化ListInitiate(L)
void ListInitiate(SeqList* L)
{
L->size = 0;
}
//求当前元素个数(L)
int ListLength(SeqList* L)
{
return L->size;
}
//插入数据元素ListInsert(L,i,x) (前插)
int ListInsert(SeqList* L, int i, DateType x)
{
if (L->size >= MaxSize)
{
printf("顺序表已满,无法插入!");
return 0;
}
else if (i<0 || i>L->size)
{
printf("插入位置不正确!");
return 0;
}
else
{
for (int j = L->size; j > i; j--)
{
L->list[j] = L->list[j - 1];
}
L->list[i] = x;
L->size++;
return 1;
}
}
//删除数据元素ListDelete(L,i,x)
int ListDelect(SeqList* L, int i,DataType* x)
{
int j;
if (L->size <= 0)
{
printf("当前顺序表中无数据可以删除!");
return 0;
}
else if (i<0 || i>=L->size)
{
printf("删除位置错误!");
return 0;
}
else
{
*x = L->list[i];
for ( j = i + 1; j < L->size; j++)
{
L->list[j-1] = L->list[j];
}
L->size--;
return 1;
}
}
//取数据元素ListGet(L,i,x)
int ListGet(SeqList* L, int i, DataType* x)
{
if (i<0 ||i>=L->size)
{
printf("所取数据不存在!");
return 0;
}
else
{
*x = L->list[i];
return 1;
}
}
Test1.c
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef int DateType;
#include"SeqList.h"
void main()
{
SeqList mylist;
int i, x=0;
//创建一个顺序表
ListInitiate(&mylist);
//将1-10顺序插入顺序表中
for (i = 0; i < 10; i++)
{
ListInsert(&mylist, i, i + 1);
}
//删除第五个元素,并打印删除的元素
ListDelete(&mylist, 4, &x);
printf("%d\n", x);
//显示顺序表的当前数据元素
for (i = 0; i < ListLength(&mylist); i++)
{
ListGet(&mylist, i, &x);
printf("%d ", x);
}
}
Test2.c
#include<stdio.h>
#define MaxSize 100
typedef struct Student
{
long number;
char name[10];
char sex[3];
int age;
}StudentType;
typedef StudentType DateType;
#include"SeqList.h"
void main()
{
SeqList myList;
int i;
StudentType s;
StudentType x[3] = { {2000001,"张三","男",20},
{2000002,"李四","男",21},
{2000003,"王五","女",22} };
ListInitiate(&myList);
ListInsert(&myList, 0, x[0]);
ListInsert(&myList, 1, x[1]);
ListInsert(&myList, 2, x[2]);
for (i = 0; i < ListLength(&myList); i++)
{
ListGet(&myList, i, &s);
printf("%d %s %s %d\n", s.number, s.name, s.sex, s.age);
}
}