// 空间不够时动态增容
void
CheckCapacity(
PSeqList
pSeqList
)
{
if
(
pSeqList
->last ==
pSeqList
->iCapacity)
{
pSeqList
->pData = (
DataType
*)realloc(
pSeqList
->pData,
pSeqList
->iCapacity +
DEFAULT_INT
);
pSeqList
->iCapacity =
pSeqList
->iCapacity +
DEFAULT_INT
;
}
}
//初始化顺序表
void
InitSeqListD(
PSeqList
pSeqList
)
{
assert
(
pSeqList
);
pSeqList
->pData = (
DataType
*)malloc(
INIT_SIZE
*
sizeof
(
DataType
));
memset(
pSeqList
->pData, 0,
INIT_SIZE
*
sizeof
(
DataType
));
pSeqList
->iCapacity =
INIT_SIZE
;
pSeqList
->last = -1;
}
// 尾部插入
void
PushBack(
PSeqList
pSeqList
,
DataType
data
)
{
int
end =
pSeqList
->last;
assert
(
pSeqList
);
CheckCapacity(&
pSeqList
);
pSeqList
->pData[end+1] =
data
;
pSeqList
->last++;
}
// 尾部删除
void
PopBack(
PSeqList
pSeqList
)
{
int
end =
pSeqList
->last;
assert
(
pSeqList
->last > 0);
pSeqList
->pData[end] = 0;
pSeqList
->last--;
}
// 头部插入
void
PushFront(
PSeqList
pSeqList
,
DataType
data
)
{
int
begin = 0;
int
end =
pSeqList
->last;
assert
(
pSeqList
);
CheckCapacity(&
pSeqList
);
for
(end =
pSeqList
->last; end>=begin; end--)
{
pSeqList
->pData[end+1] =
pSeqList
->pData[end];
}
pSeqList
->pData[begin] =
data
;
pSeqList
->last++;
}
// 头部删除
void
PopFront(
PSeqList
pSeqList
)
{
int
begin = 0;
assert
(
pSeqList
!=
NULL
);
for
(begin = 0; begin <=
pSeqList
->last; begin++)
{
pSeqList
->pData[begin] =
pSeqList
->pData[begin + 1];
}
pSeqList
->last--;
}
// 销毁动态顺序表
void
DestroyList(
PSeqList
pSeqList
)
{
pSeqList
->iCapacity = 0;
pSeqList
->last = 0;
free(
pSeqList
->pData);
pSeqList
->pData =
NULL
;
}
// 改变顺序表中元素的个数,Size为元素的个数
void
ReSize(
PSeqList
pSeqList
,
int
Size
)
{
assert
(
pSeqList
);
if
(
Size
<
pSeqList
->last)
{
//新分配元素个数小于顺序表长度,为缩小,顺序表长度,容量均改变
pSeqList
->pData = (
DataType
*)realloc(
pSeqList
->pData,
Size
*
sizeof
(
DataType
));
pSeqList
->last=
Size
;
pSeqList
->iCapacity =
Size
;
}
else
{
//如果新分配元素个数大于顺序表长度,顺序表长度不变,容量改
pSeqList
->pData = (
DataType
*)realloc(
pSeqList
->pData,
Size
*
sizeof
(
DataType
));
pSeqList
->iCapacity =
Size
;
}
}
void
Print(
PSeqList
pSeqList
)
{
int
begin = 0;
for
(begin = 0; begin <=
pSeqList
->last; begin++)
{
printf(
"%d\n"
,
pSeqList
->pData[begin]);
}
return
pSeqList
;
}