代码实现
#define _CRT_SECURE_NO_WARNINGS
#include"Seplist.h"
//初始化、销毁、打印
void SLInit(SL* ps)
{
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SLDestory(SL* ps)
{
;
}
void SLPrint(SL* ps)
{
for (int i = 0;i < ps->size;i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
//扩容
void SLCheckCapacity(SL* ps)
{
if (ps->size == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
if (tmp == NULL)
{
perror("realloc fail");
exit(1);//程序终止
}
//扩容成功
ps->a = tmp;
ps->capacity = newcapacity;
}
}
//尾、头部插入和删除
void SLPushBack(SL* ps, SLDataType x)//尾插
{
assert(ps);//传入的为非空指针
SLCheckCapacity(ps);//判断是否扩容
ps->a[ps->size++] = x;//空间充足直接插入
}
void SLPopBack(SL* ps)//尾删
{
assert(ps);
assert(ps->size);//顺序表不为空
ps->size--;
}
void SLPushFront(SL* ps, SLDataType x)//头插
{
assert(ps);
SLCheckCapacity(ps);
for (int i = ps->size;i > 0;i--)
{
ps->a[i] = ps->a[i - 1];
}
ps->a[0] = x;
ps->size++;
}
void SLPopFront(SL* ps)//头删
{
assert(ps);
assert(ps->size);
for (int i = 0;i < ps->size - 1;i++)
{
ps->a[i] = ps->a[i + 1];
}
ps->size--;
}
//指定位置插删
void SLInsert(SL* ps, int pos, SLDataType x)
{
assert(ps);
assert(pos > 0 && pos <= ps->size );
SLCheckCapacity(ps);
for (int i = ps->size;i > pos;i--)
{
ps->a[i] = ps->a[i - 1];
}
ps->a[pos] = x;
ps->size++;
}
//删除指定位置
void SLErase(SL* ps, int pos)
{
assert(ps);
assert(pos >= 0 && pos < ps->size);
for (int i = pos;i < ps->size - 1;i++)
{
ps->a[i] = ps->a[i + 1];//ps->arr[i-2] = ps->arr[i-1];
}
ps->size--;
}
头文件
#pragma once
2 #include<stdio.h>
3 #include<stdlib.h>
4 #include<assert.h>
5
6 typedef int SLDataType;//int重命名
7
8 typedef struct Seplist
9 {
10 SLDataType* a;
11 int size;//有效数据个数
12 int capacity;//空间容量
13 }SL;
14
15 //初始化和销毁及顺序表打印
16 void SLInit(SL* ps);
17 void SLDestory(SL* ps);
18 void SLPrint(SL* ps);
19
20 //扩容
21 void SLCheckCapacity(SL* ps);
22
23 //尾、头部插入和删除
24 void SLPushBack(SL* ps, SLDataType x);
25 void SLPopBack(SL* ps);
26 void SLPushFront(SL* ps, SLDataType x);
27 void SLPopFront(SL* ps);
代码测试
#define _CRT_SECURE_NO_WARNINGS
2 #include"Seplist.h"
3 void test()
4 {
5 SL sl;
6 SLInit(&sl);
7 SLPushBack(&sl, 1);
8 SLPushBack(&sl, 2);
9 SLPushBack(&sl, 3);
10 SLPushBack(&sl, 4);
11 SLPrint(&sl);//β
12
13 SLPopBack(&sl);
14 SLPopBack(&sl);
15 SLPrint(&sl);//βɾ
16
17 SLPushFront(&sl, 5);
18 SLPushFront(&sl, 6);
19 SLPushFront(&sl, 7);
20 SLPrint(&sl);//ͷ
21
22 SLPopFront(&sl);
23 SLPopFront(&sl);
24 SLPrint(&sl);//ͷɾ
25
26 }
27
28 int main()
29 {
30 test();
31 return 0;
32 }