#define _CRT_SECURE_NO_WARNINGS
2 #include"Seplist.h"
3
4 //初始化、销毁、打印
5 void SLInit(SL* ps)
6 {
7 ps->a = NULL;
8 ps->size = ps->capacity = 0;
9 }
10
11 void SLDestory(SL* ps)
12 {
13 ;
14 }
15
16 void SLPrint(SL* ps)
17 {
18 for (int i = 0;i < ps->size;i++)
19 {
20 printf("%d ", ps->a[i]);
21 }
22 printf("\n");
23 }
24
25 //扩容
26 void SLCheckCapacity(SL* ps)
27 {
28 if (ps->size == ps->capacity)
29 {
30 int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
31 SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity * sizeof(SLDataType));
32 if (tmp == NULL)
33 {
34 perror("realloc fail");
35 exit(1);//程序终止
36 }
37 //扩容成功
38 ps->a = tmp;
39 ps->capacity = newcapacity;
40 }
41 }
42
43 //尾、头部插入和删除
44 void SLPushBack(SL* ps, SLDataType x)//尾插
45 {
46 assert(ps);//传入的为非空指针
47 SLCheckCapacity(ps);//判断是否扩容
48 ps->a[ps->size++] = x;//空间充足直接插入
49 }
50 void SLPopBack(SL* ps)//尾删
51 {
52 assert(ps);
53 assert(ps->size);//顺序表不为空
54 ps->size--;
55 }
56 void SLPushFront(SL* ps, SLDataType x)//头插
57 {
58 assert(ps);
59 SLCheckCapacity(ps);
60 for (int i = ps->size;i > 0;i--)
61 {
62 ps->a[i] = ps->a[i - 1];
63 }
64 ps->a[0] = x;
65 ps->size++;
66 }
67 void SLPopFront(SL* ps)//头删
68 {
69 assert(ps);
70 assert(ps->size);
71 for (int i = 0;i < ps->size - 1;i++)
72 {
73 ps->a[i] = ps->a[i + 1];
74 }
75 ps->size--;
76 }
77
78 //指定位置插删
79 void SLInsert(SL* ps, int pos, SLDataType x)
80 {
81 assert(ps);
82 assert(pos > 0 && pos <= ps->size );
83
84 SLCheckCapacity(ps);
85
86 for (int i = ps->size;i > pos;i--)
87 {
88 ps->a[i] = ps->a[i - 1];
89 }
90 ps->a[pos] = x;
91 ps->size++;
92 }
93 //删除指定位置
94 void SLErase(SL* ps, int pos)
95 {
96 assert(ps);
97 assert(pos >= 0 && pos < ps->size);
98 for (int i = pos;i < ps->size - 1;i++)
99 {
100 ps->a[i] = ps->a[i + 1];//ps->arr[i-2] = ps->arr[i-1];
101 }
102 ps->size--;
103 }
#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);