用一个数组实现两个栈,在某些场景下可以节省内存。
【思路】
栈一在数组头部开始入栈并更新top,栈二在数组尾部入栈并更新rear(初始值为数组最尾index)。
top和rear接头的时候,两栈全满。
【代码实现】
#ifndef __STACK_DOUBLE__H__
#define __STACK_DOUBLE__H__
#define DSTACK_ISEMPTY_FRONT(st) (st->top == -1)
#define DSTACK_ISEMPTY_REAR(st) (st->rear == st->capability)
#define DSTACK_ISFULL(st) (st->top == (st->rear-1))
// front push
static inline void fpush(stack_t *st, int data)
{
//if NULL
if (DSTACK_ISFULL(st)) assert(0); // in fact, don't be assert
st->arr[++st->top] = data;
}
// rear push
static inline void rpush(stack_t *st, int data)
{
//if NULL
if (DSTACK_ISFULL(st)) assert(0); // in fact, don't be assert
st->arr[--st->rear] = data;
}
// front pop
static inline int fpop(stack_t *st)
{
//if NULL
if (!DSTACK_ISEMPTY_FRONT(st)) {
return st->arr[(st->top--)];
}
}
// rear pop
static inline int rpop(stack_t *st)
{
//if NULL
if (!DSTACK_ISEMPTY_REAR(st)) {
return st->arr[st->rear++];
}
}
// front top
static inline int ftop(stack_t *st)
{
//if NULL
if (!DSTACK_ISEMPTY_FRONT(st)) {
return st->arr[(st->top)];
}
}
// rear top
static inline int rtop(stack_t *st)
{
//if NULL
if (!DSTACK_ISEMPTY_FRONT(st)) {
return st->arr[st->rear];
}
}
#endif
【测试用例】
int dtest_stack_arr()
{
stack_t *st = stack_create(TEST_ELEM_MAX_LEN);
//if !st
int i = 0;
// 向第一个栈压入部分数据。
for (i=0; i<TEST_ELEM_MAX_LEN/2; i++) {
fpush(st, i);
}
// 向第二个栈压入部分数据。
for (; i<TEST_ELEM_MAX_LEN; i++) {
rpush(st, i);
}
// 将两个栈分别pop。
for (i=0; i<TEST_ELEM_MAX_LEN/2; i++) {
//printf("top: %d\n", ftop(st));
printf("ftop: %d\n", fpop(st));
printf("rtop: %d\n", rpop(st));
printf("\n");
}
stack_destroy(st);
return 0;
}
int main()
{
dtest_stack_arr();
return 0;
}
【测试结果】
./a.out
ftop: 4
rtop: 9
ftop: 3
rtop: 8
ftop: 2
rtop: 7
ftop: 1
rtop: 6
ftop: 0
rtop: 5