1.为什么需要数据结构?
- // SeqList.h
-
- #pragma once
- #include
- #include
- #include
-
- typedef int SLDataType;
- typedef struct SeqList
- {
- SLDataType* arr;
- int size;
- int capacity;
-
- }SL;
- //typedef struct SeqList SL;
-
- //顺序表初始化
- void SLInit(SL* ps);
- //顺序表销毁头部插入
- void SLDestroy(SL* ps);
-
- //数据打印
- void SLprint(SL sl);
-
- //插入数据之前先看空间够不够
- void SLCheckCapacity(SL* ps);
-
- //尾部插入&头部插入
- //尾部插入
- void SLPushback(SL* ps, SLDataType x);
- //头部插入
- void SLPushFront(SL* ps, SLDataType x);
-
- //尾部删除&头部删除
- //尾部删除
- void SLPopBack(SL* ps);
- //头部删除
- void SLPopFront(SL* ps);
- //SeqList.c
-
- #define _CRT_SECURE_NO_WARNINGS 1
- #include "SeqList.h"
-
- //顺序表初始化
- void SLInit(SL* ps)
- {
- ps->arr = NULL;
- ps->size = 0;
- ps->capacity = 0;
- }
- //顺序表销毁
- void SLDestroy(SL* ps)
- {
- if (ps->arr)
- {
- free(ps->arr);
- }
- ps->arr = NULL;
- ps->size = 0;
- ps->capacity = 0;
- }
-
- //插入数据之前先看空间够不够
- void SLCheckCapacity(SL* ps)
- {
- if (ps->capacity == ps->size)//空间不够了 需要申请内存
- {
- int Newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
- SLDataType* temp = realloc(ps->arr, Newcapacity * sizeof(SLDataType));
- if (temp == NULL)
- {
- perror("realloc");
- exit(1);
- //return 1;
- }
- ps->arr = temp;//内存申请成功
- ps->capacity = Newcapacity;
- }
- }
- //数据打印
- void SLprint(SL sl)
- {
- for (int i = 0; i < sl.size; i++)
- {
- printf("%d ", sl.arr[i]);
- }
- printf("\n");
- }
- //尾部插入
- void SLPushback(SL* ps, SLDataType x)
- {
- assert(ps);
- SLCheckCapacity(ps);
- //ps->arr[ps->size] = x;
- //++ps->size;
- ps->arr[ps->size++] = x;
- }
- //头部插入
- void SLPushFront(SL* ps, SLDataType x)
- {
- assert(ps);
- SLCheckCapacity(ps);
- //先让顺序表中已有的数据整体往后挪动一位
- for (int i = ps->size;i>0; i--)
- {
- ps->arr[i] = ps->arr[i - 1];//arr[1]=arr[0]
- }
- ps->arr[0] = x;
- ps->size++;//长度+1
- }
-
- //尾部删除
- void SLPopBack(SL* ps)
- {
- assert(ps);
- ps->size--;//--ps->size
- }
- //头部删除
- void SLPopFront(SL* ps)
- {
- assert(ps);
- for (int i = 0; i < ps->size - 1; i++)
- {
- ps->arr[i] = ps->arr[i + 1];
- }
- ps->size--;
- }
- //SeqList-test.c
-
-
- #define _CRT_SECURE_NO_WARNINGS 1
- #include"SeqList.h"
-
-
- void test()
- {
- SL sl;
- SLInit(&sl);//初始化
-
- SLPushback(&sl, 1);//尾插一个数字1
- SLPushback(&sl, 2);//尾插一个数字1
- SLPushback(&sl, 3);//尾插一个数字1
- SLPushback(&sl, 4);//尾插一个数字1
- SLprint(sl);//1 2 3 4
-
- SLPushFront(&sl, 0); //头插一个数字0
- SLprint(sl);//0 1 2 3 4
-
- SLPopBack(&sl);//尾删一个数字
- SLprint(sl);//0 1 2 3
-
- SLPopFront(&sl);//头删一个数字
- SLprint(sl);//1 2 3
-
- SLDestroy(&sl);
- }
-
- int main()
- {
- test();
-
- return 0;
- }