順序表的概念/數據結構部分請見上一節,這裏直接貼出書上的算法和代碼
需要注意的是這裏的realloc函數的用法,參考MAN手冊就好
另外接口只保證了編譯通過,請自行寫測試用例測試
#ifndef __HEADER_H__
#define __HEADER_H__ 100
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <strings.h>
#define DEBUG 100
#ifdef DEBUG
#define PRINT_INFO(format,...) printf(format,##__VA_ARGS__)
#else
#define PRINT_INFO(format,...)
#endif
#define PRINT_ERR(format,args...) printf(format,##args)
#define SUCCESS 0
#define FAILURE -1
/*type define*/
typedef struct
{
int* elem;
int length;
int listsize;
} sqlist;
/*func declaration*/
void print_sqlist(sqlist* L);//print
int init_sqlist(sqlist* L);//init
int insert_sqlist(sqlist* L, int pos, int value);//insert
int delete_sqlist(sqlist* L, int pos);//delete elem
void destroy_sqlist(sqlist* L);//destroy
#endif /*__HEADER_H__*/
int init_sqlist(sqlist* L)
{
/*CHECKPOINTER*/
assert(L != NULL);
L->elem = (int*)malloc(LIST_INIT_SIZE * sizeof(int));
if(L->elem == NULL)
{
PRINT_ERR("[init_sqlist]malloc failed!\n");
return FAILURE;
}
PRINT_INFO("[init_sqlist]malloc success!\n");
L->length = 0;
L->listsize = LIST_INIT_SIZE;
return SUCCESS;
}
/*pos counted from 1*/
int insert_sqlist(sqlist* L, int pos, int value)
{
int* p_start = NULL;
int* q_end = NULL;
int* temp = NULL;
/*CHECKPOINTER*/
assert(L != NULL);
/*check params*/
if(pos < 1 || pos > L->length + 1)
{
PRINT_ERR("[insert_sqlist]invalid pos:%d\n", pos);
return FAILURE;
}
if(L->length == L->listsize)
{
PRINT_INFO("[insert_sqlist]sqlist full, need to expand!\n");
temp = L->elem;
L->elem = (int*)realloc(L->elem, (L->listsize + LISTINCREMENT) * sizeof(int));//realloc
if(L->elem == NULL)
{
PRINT_ERR("[insert_sqlist]realloc failed!\n");
free(temp);
temp = NULL;
return FAILURE;
}
PRINT_INFO("[insert_sqlist]realloc success!\n");
temp = NULL;
L->listsize += LISTINCREMENT;
}
for(p_start = &L->elem[pos - 1],q_end = &L->elem[L->length- 1]; q_end >= p_start; q_end--)
{
*(q_end + 1) = *q_end;
}
*p_start = value;
L->length += 1;
return SUCCESS;
}
/*pos counted fom 1*/
int delete_sqlist(sqlist* L, int pos)
{
int* p_start = NULL;
int* q_end = NULL;
/*CHECKPOINTER*/
assert(L != NULL);
/*check param*/
if(pos < 1 || pos > L->length)
{
PRINT_ERR("[delete_sqlist]invalid pos:%d\n", pos);
return FAILURE;
}
if(L->length == 0)
{
PRINT_ERR("[delete_sqlist]empty sqlist, cannot delete elem!\n");
return FAILURE;
}
for(p_start = &L->elem[pos - 1], q_end = &L->elem[L->length - 1]; q_end > p_start; p_start++)
{
*p_start = *(p_start + 1);
}
L->length -= 1;
return SUCCESS;
}
void destroy_sqlist(sqlist* L)
{
/*CHECKPOINTER*/
assert(L != NULL);
if(L->elem != NULL)
{
free(L->elem);
L->elem = NULL;
}
L->length = 0;
L->listsize = 0;
return;
}
void print_sqlist(sqlist* L)
{
int i = 0;
/*CHECKPOINTER*/
assert(L != NULL);
for(i = 0; i < L->length; i++)
{
PRINT_INFO("L->elem[%d] = %d\n", i, L->elem[i]);
}
return;
}