用c语言实现一个静态的顺序表结构,读者注意我的编码风格
#include<stdio.h>
#include<assert.h>
#define MAX_SIZE 10 //以后更改顺序表大小方便
#define DateType int //这样定义方便以后存取其他类型数据时更改方便
typedef struct SeqList{
DateType array[MAX_SIZE];
int size;
}SeqList, *PSeqList;//在穿参数的时候直接传递结构体传递结构体开销很大
void InitSeqList(PSeqList pSeq)
{
assert(pSeq);
for (pSeq->size = 0; pSeq->size < MAX_SIZE, pSeq->size++)
{
pSeq->array[pSeq->size] = 0;
}
pSeq->size = 0;
}
void SeqListPushBack(PSeqList pSeq, DateType data)
{
assert(pSeq);
if (pSeq->size >= MAX_SIZE)
{
printf("顺序表已满!\n");
return;
}
pSeq->array[pSeq->size] = data;
pSeq->size++;
}
void SeqListPopBack(PSeqList pSeq)
{
assert(pSeq);
if (pSeq->size == 0)
{
printf("顺序表已空!\n");
return;
}
pSeq->size--;
}
void SeqListPushFront(PSeqList pSeq, DateType data)
{
assert(pSeq);
if (pSeq->size >= MAX_SIZE)
{
printf("顺序表已满!\n");
return;
}
for (int i = pSeq->size; i >= 0; i--)
{
pSeq->array[i] = pSeq->array[i - 1];
}
pSeq->size++;
}
void SeqListPopFront(PSeqList pSeq)
{
assert(pSeq);
if (pSeq->size = 0)
{
printf("顺序表已为空!\n");
return;
}
for (int i = 1; i < pSeq->size; i++)
{
pSeq->array[i - 1] == pSeq->array[i];
}
pSeq->size--;
}
void SeqListPushInsert(PSeqList pSeq, int where, DateType data)
{
assert(pSeq);
if (pSeq->size >= MAX_SIZE)
{
printf("顺序表已满!\n");
return;
}
if (where < 0 && where >= pSeq->size)
{
printf("插入的位置错误!\n");
return;
}
for (int i = pSeq->size; i>where; i++)
{
pSeq->array[i] = pSeq->array[i - 1];
}
pSeq->size++;
}
void SeqListPopInsert(PSeqList pSeq, int where)
{
assert(pSeq);
if (pSeq->size = 0)
{
printf("顺序表已为空!\n");
return;
}
if (where < 0)
{
printf("弹出的位置有误!\n");
return;
}
for (int i = where; i < pSeq->size; i++)
{
pSeq->array[i] = pSeq->array[i + 1];
}
pSeq->size--;
}
//时间复杂度:O(N)
//空间复杂度:O(1)
//这里还可以定义一个数组用来临时存放数据,把需要的数据存放起来,遍历完后再放回去,不过太low了
void RemoveAll(PSeqList pSeq,DateType data)
{
assert(pSeq);
int count = 0;
int i = 0;//循环变量
for (; i < pSeq->size; i++)
{
if (pSeq->array[i] != data)
{
pSeq->array[i] = pSeq->array[i - count];
}
else
{
count++;
}
}
pSeq->size -= count;
}
void swap(int *x, int *y)
{
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
//Select_sort_C
void SelectSort(PSeqList pSeq)
{
int Maxpos = 0;
int i = 0, j = 0;//循环变量
for (; i < pSeq->size - 1; i++)
{
Maxpos = 0;
for (j = 0; j < pSeq->size - i; j++)
{
if (pSeq->array[j]>pSeq->array[Maxpos])
Maxpos = j;
}
swap(&pSeq->array[pSeq->size - 1], &pSeq->array[Maxpos]);
}
}
注:我在这里没有写测试代码