seqlist.h:
#pragma once
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct Seqlist {
type* data;
int size;
int capacity;
}sl;
//初始化顺序表
void initialize(sl* ps);
//销毁线性表
void destory(sl* ps);
//判断是否满员;
void isfull(sl* ps);
//头插数据
void headinsert(sl* ps);
//尾插数据
void tailinsert(sl* ps);
//头删数据
void headdelete(sl* ps);
//尾删数据
void taildelete(sl* ps);
//打印结果
void print(sl ps);
seqlist.c:
#include"seqlist.h"
void initialize(sl* ps){//初始化顺序表
ps->data = NULL;
ps->size = ps->capacity = 0;
}
void destory(sl* ps) {销毁顺序表
if (ps->data) {
free(ps->data);
ps->data = NULL;
}
ps->size = ps->capacity = 0;
}
void isfull(sl* ps) {
if (ps->size == ps->capacity) {//如果当前数量达到容量
int newcapacity =ps->capacity== 0 ? 4 : 2 * ps->capacity;//未创建初始容量则是4,创建了则是扩容到当前容量的两倍
type* p = (type*)realloc(ps->data, newcapacity * sizeof(type));//开辟空间
if (p == NULL) {
perror("申请失败");
return;
}
ps->data = p;//指针重新赋值保证有效;
ps->capacity = newcapacity;
}
}
void headinsert(sl* ps,type c) {//头插法
assert(ps);//避免指针为空
isfull(ps);//判断是否容量已满,满了则扩容
for (int i = ps->size; i>=1; i--) {
ps->data[i] = ps->data[i-1];
}
ps->data[0] = c;
ps->size++;}
void tailinsert(sl* ps,type c) {//尾插法
assert(ps);
ps->data[ps->size++] = c;
}
void headdelete(sl* ps){//头删法
if (ps->data) {
for (int i = 0; i<=ps->size-2; i++) {
ps->data[i] = ps->data[i + 1];
}
ps->size--;
}
}
void taildelete(sl* ps){//尾删法
assert(ps);
ps->size--;}
void print(sl ps) {//打印
for (int i = 0; i < ps.size; i++) {
printf("%d", ps.data[i]);
}
printf("\n");
}
测试样例