实现顺序表的头文件seqList.h
typedef int SLDataType;
typedef struct seqList{
SLDataType* _data;
size_t _size;
size_t _capacity;
}seqList;
void initSeqList(seqList* sl);
void push_back(seqList* sl, SLDataType val);
void checkCapacity(seqList* sl);
void printSeqList(seqList* sl);
void pop_back(seqList* sl);
void push_front(seqList* sl);
void pop_front(seqList* sl);
void insert(seqList* sl, size_t pos, SLDataType val);
void erase(seqList* sl, int pos);
bool empty(seqList* sl);
int size(seqList* sl);
int find(seqList* sl, SLDataType val);
void destroySeqList(seqList* sl);
顺序表的代码实现
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#include"seqList.h"
void initSeqList(seqList* sl){
assert(sl);
sl->_data = NULL;
sl->_size = sl->_capacity = 0;
}
void push_back(seqList* sl,SLDataType val){
assert(sl);
checkCapacity(sl);
sl->_data[sl->_size] = val;
++sl->_size;
}
void checkCapacity(seqList* sl){
if (sl == NULL)
return;
if (sl->_size == sl->_capacity){
int newCapacity = sl->_capacity == 0 ? \
1:2 * sl->_capacity;
sl->_data = (SLDataType*)realloc(sl->_data, sizeof(SLDataType)*newCapacity);
sl->_capacity = newCapacity;
}
}
void printSeqList(seqList* sl){
if (sl == NULL)
return;
for (int i = 0; i < sl->_size; ++i){
printf("%d ", sl->_data[i]);
}
printf("\n");
}
void pop_back(seqList* sl){
if (sl == NULL)
return;
if (sl->_size>0)
--(sl->_size);
}
void push_front(seqList* sl,SLDataType val){
if (sl == NULL)
return;
checkCapacity(sl);
int end = sl->_size;
while (end>0){
sl->_data[end] = sl->_data[end - 1];
--end;
}
sl->_data[0] = val;
++sl->_size;
}
void pop_front(seqList* sl){
if (sl == NULL)
return;
if (sl->_size == 0)
return;
int start = 1;
while (start < sl->_size){
sl->_data[start - 1] = sl->_data[start];
++start;
}
--(sl->_size);
}
void insert(seqList* sl, size_t pos, SLDataType val){
if (sl == NULL) return;
if (pos >= 0 && pos <= sl->_size){
checkCapacity(sl);
int end = sl->_size;
while (end > pos){
sl->_data[end] = sl->_data[end - 1];
end--;
}
sl->_data[pos] = val;
++(sl->_size);
}
}
void erase(seqList* sl, int pos){
if (sl == NULL || sl->_size == 0)
return;
if (pos >= 0 && pos < sl->_size){
int start = pos;
while (start<(sl->_size-1)){
sl->_data[start] = sl->_data[start + 1];
start++;
}
--(sl->_size);
}
}
bool empty(seqList* sl){
if (sl == NULL || sl->_size == 0)
return true;
else
return false;
}
int size(seqList* sl){
if (sl == NULL)
return 0 ;
return sl->_size;
}
int find(seqList* sl, SLDataType val){
if (sl == NULL)
return 0;
int i = 0;
for (; i < sl->_size; ++i){
if (sl->_data[i] == val)
return i;
}
return -1;
}
void destroySeqList(seqList* sl){
if (sl == NULL)
return;
if (sl->_data){
free(sl->_data);
sl->_data = NULL;
}
}
测试案例
void test(){
seqList sl;
initSeqList(&sl);
}
int main(){
test();
system("pause");
return 0;
}