栈
栈是在一端进行插入操作和删除操作的线性表(俗称堆栈),允许进行操作的一端称为“栈顶”,另一固定端称为“栈底”,当栈中没有元素称为“空栈”。特点:后进先出(LIFO)。
顺序栈:
顺序栈是栈的顺序实现。顺序栈是指利用顺序存储结构实现的栈。采用地址连续的存储空间(数组)依次存储栈中数据元素,由于入栈和出栈运算都是在栈顶进行,而栈底位置是固定不变的,可以将栈底位置设置在数组空间的起始处;栈顶位置是随入栈和出栈操作而变化的,故需用一个整型变量top来记录当前栈顶元素在数组中的位置。
基本运算:
- 创建空栈: CreateStack(len)
sqstack *stack_create(int len)
{
sqstack *s;
if((s = (sqstack *)malloc(sizeof(sqstack))) == NULL){
printf("malloc failed\n");
return NULL;
}
if((s->data = (datatype *)malloc(len * sizeof(datatype))) == NULL){
printf("malloc failed\n");
return NULL;
}
s->maxlen = len;
s->top = -1;
return s;
}
- 清空栈: ClearStack(S)
void stack_clear(sqstack *s)
{
s->top = -1;
}
- 判断是否空栈: EmptyStack(S)
int stack_empty(sqstack *s)
{
return (s->top == -1 ? 1 : 0;);
}
- 判断是否栈满: FullStack(S)
int stack_full(sqstack *s)
{
return (s->top == s->maxlen - 1 ? 1 : 0;);
}
- 元素进栈: PushStack(S, x)
int stack_push(sqstack *s, datatype value)
{
if(s->top == s->maxlen - 1)
{
printf("stack is full\n");
return -1;
}
s->data[s->top + 1] = value;
s->top++;
return 1;
}
- 元素出栈: PopStack(S)
datatype stack_pop(sqstack *s)
{
s->top--;
return s->data[s->top + 1];
}
- 取栈顶元素: GetTop(S)
datatype stack_top(sqstack *s)
{
return (s->data[s->top]);
}
example
typedef int datatype;
typedef struct{
datatype *data;
int maxlen;
int top;
}sqstack;
sqstack *stack_create(int len);
int stack_empty(sqstack *s):
void stack_clear(sqstack *s);
int stack_full(sqstack *s):
int stack_push(sqstack *s, datatype value):
datatype stack_pop(sqstack *s);
datatype stack_top(sqstack *s);
sqstack *stack_create(int len)
{
sqstack *s;
if((s = (sqstack *)malloc(sizeof(sqstack))) == NULL){
printf("malloc failed\n");
return NULL;
}
if((s->data = (datatype *)malloc(len * sizeof(datatype))) == NULL){
printf("malloc failed\n");
return NULL;
}
s->maxlen = len;
s->top = -1;
return s;
}
/*栈为空返回1*/
int stack_empty(sqstack *s)
{
return (s->top == -1 ? 1 : 0;);
}
void stack_clear(sqstack *s)
{
s->top = -1;
}
int stack_full(sqstack *s)
{
return (s->top == s->maxlen - 1 ? 1 : 0;);
}
int stack_push(sqstack *s, datatype value)
{
if(s->top == s->maxlen - 1)
{
printf("stack is full\n");
return -1;
}
s->data[s->top + 1] = value;
s->top++;
return 1;
}
datatype stack_pop(sqstack *s)
{
s->top--;
return s->data[s->top + 1];
}
datatype stack_top(sqstack *s)
{
return (s->data[s->top]);
}
void stack_free(sqstack *s)
{
free(s->data);
s->data = NULL;
free(s);
s = NULL;
}
int main(int argc, const char *argv[])
{
sqstack *s;
int n = 10;
s = stack_create();
stack_push(s,10);
stack_push(s,20);
stack_push(s,30);
stack_push(s,40);
while(!stack_empty(s))
{
printf("%d",stack_pop(s));
}
puts("");
return 0;
stack_free(s);
}