简单起见,我们创建一个大小为 100 ,数组存储的顺序表来做演示
#define SEQUENCE_SIZE 100
typedef struct
{
int length;
int data[SEQUENCE_SIZE];
}sqlist, *psqlist;
void init(psqlist p)
{
p->length = 0;
for (int i = 0; i < SEQUENCE_SIZE; i++)
p->data[i] = 0;
}
void insert(psqlist list, int elem);
void insert(psqlist p, int elem)
{
p->data[p->length++] = elem;
}
void delete(psqlist list, int position);
void delete(psqlist p, int position)
{
if (check_position(p, position) == 0)
return;
for (int i = position; i < p->length - 1; i++)
p->data[i] = p->data[i + 1];
p->data[p->length--] = 0;
}
void modify(psqlist list, int position, int elem);
void modify(psqlist p, int position, int elem)
{
if (check_position(p, position) == 1)
p->data[position] = elem;
}
void display(psqlist list);
void display(psqlist p)
{
printf("The List Length is %d\n", p->length);
for (int i = 0; i < p->length; i++)
printf("%-3d", p->data[i]);
printf("\n");
}
sequence.h
#ifndef SEQUENCE_H
#define SEQUENCE_H
#define SEQUENCE_SIZE 100
typedef struct
{
int length;
int data[SEQUENCE_SIZE];
}sqlist, *psqlist;
void init(psqlist list);
void insert(psqlist list, int elem);
void delete(psqlist list, int position);
void display(psqlist list);
void modify(psqlist list, int position, int elem);
int check_position(psqlist list, int position);
#endif
sequence.c
# include
# include "sequence.h"
int main() {
sqlist list;
psqlist plist = &list;
init(plist);
printf("\n---------------------\n");
printf("before insert action:\n");
printf("---------------------\n");
display(plist);
insert(plist, 1);
insert(plist, 2);
insert(plist, 3);
insert(plist, 4);
printf("---------------------\n");
printf("after insert action:\n");
printf("---------------------\n");
display(plist);
printf("\n---------------------\n");
printf("before delete action:\n");
printf("---------------------\n");
display(plist);
delete(plist, 1);
printf("---------------------\n");
printf("after delete action\n");
printf("---------------------\n");
display(plist);
printf("\n---------------------\n");
printf("before modify action\n");
printf("---------------------\n");
display(plist);
modify(plist, 2, 111);
printf("---------------------\n");
printf("after modify action\n");
printf("---------------------\n");
display(plist);
}
void init(psqlist p)
{
p->length = 0;
for (int i = 0; i < SEQUENCE_SIZE; i++)
p->data[i] = 0;
}
void insert(psqlist p, int elem)
{
p->data[p->length++] = elem;
}
void delete(psqlist p, int position)
{
if (check_position(p, position) == 0)
return;
for (int i = position; i < p->length - 1; i++)
p->data[i] = p->data[i + 1];
p->data[p->length--] = 0;
}
void display(psqlist p)
{
printf("The List Length is %d\n", p->length);
for (int i = 0; i < p->length; i++)
printf("%-3d", p->data[i]);
printf("\n");
}
void modify(psqlist p, int position, int elem)
{
if (check_position(p, position) == 1)
p->data[position] = elem;
}
int check_position(psqlist p, int position)
{
if (position > p->length || position < 0)
{
return 0;
}
return 1;
}