本文使用C语言,给出了堆栈的两种实现:基于数组和基于链表的实现方式。
堆栈是一种常用的数据结构,具有“后进先出(Last In First Out)”的特性,常用来进行函数调用时候的参数传递,解决递归函数书的非递归实现,表达式中的括号匹配等问题。堆栈的常用操作如下:
- createStack(st):建立一个空栈
- push(st, x):将元素x压入栈st当中,使之成为栈顶元素
- pop(st,x):当栈非空时,将栈顶元素弹出,并赋值给x
- top(st):当栈非空时,返回栈顶元素的值
- isEmpty(st):判断栈st是否为空
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define EleType int
#define DEFAULT_SIZE 100
/**//*---------array-based stack--------------*/
#if defined(ARRAY_BASED_STACK)
typedef struct Stack_t ...{
int top;
int capacity;
EleType *container;
}Stack;
int createStack(Stack *st, int c)
...{
if(c<0)
c = DEFAULT_SIZE;
st->container = (EleType*)malloc(c*sizeof(EleType));
if(NULL == st->container) return 0;
st->capacity = c;
st->top = -1;
return 1;
}
int destoryStack(Stack *st)
...{
if(st)...{
st->top = -1;
free(st->container);
st->container = NULL;
}
return 1;
}
int isEmpty(Stack *st)
...{
if(-1 == st->top)
return 1;
else
return 0;
}
EleType top(Stack *st)
...{
return st->container[st->top];
}
int push(Stack *st, EleType e)
...{
if((st->top + 1) == st->capacity) ...{
EleType *tmp = st->container;
st->container = (EleType*)malloc(st->capacity * 2 *sizeof(EleType));
if(!(st->container)) return 0;
st->capacity <<= 1;
int i;
for(i=0; i<st->top; i++)
st->container[i] = tmp[i];
free(tmp);
}
st->top ++;
st->container[st->top] = e;
return 1;
}
int pop(Stack *st, EleType *eptr)
...{
if(-1 == st->top)...{
return 0;
}
else ...{
st->top --;
*eptr = st->container[st->top+1];
if(st->top < (st->capacity>>1)) ...{
EleType *tmp = (EleType*)malloc((st->capacity/2) *sizeof(EleType));
if(tmp) ...{
int i;
for(i=0; i<st->top; i++)
tmp[i] = st->container[i];
free(st->container);
st->container = tmp;
}
}
return 1;
}
}
#endif
/**//*------------link-based stack-------------*/
typedef struct Element_t...{
void *data;
struct Element_t *next;
}Element;
int createStack(Element **st);
int destoryStack(Element **st);
int push(Element **st, void *data);
int pop(Element **st, void **data);
int isEmpty(Element **st);
void * top(Element **st);
int createStack(Element **st)
...{
*st = NULL;
return 1;
}
int destoryStack(Element **st)
...{
Element *next = NULL;
while(*st)...{
next = (*st)->next;
free(*st);
*st = next;
}
return 1;
}
int push(Element **st, void *data)
...{
Element *tmp = (Element*)malloc(sizeof(*tmp));
if(!tmp)
return 0;
else ...{
tmp->data = data;
tmp->next = *st;
(*st)->next = tmp;
return 1;
}
}
int pop(Element **st, void **data)
...{
if(!(*st))
return 0;
else ...{
Element *t = *st;
*data = t->data;
*st = t->next;
free(t);
return 1;
}
}
int isEmpty(Element **st)
...{
if(!(*st))
return 0;
else
return 1;
}
void* top(Element **st)
...{
if(!(*st))
return (*st)->data;
else
return NULL;
}