- 棧(stack),是一種線性存儲結構,它有以下幾個特點: 棧中數據是按照"後進先出(LIFO, Last In First Out)"方式進出棧的。 向棧中添加/刪除數據時,只能從棧頂進行操作。
- 棧的基本操作
基本操作 |
---|
initStack(&S) |
clearStack(&S) |
getLength(&S) |
pushStack(&S, e) |
stackTraverse(S, visit()) |
destroyStack(&S) |
isStackEmpty(&S) |
getTop(S, &e) |
popStack(&S, &e) |
實現代碼:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define status int
#define INIT_SIZE 100
#define INCRE_SIZE 10
typedef int elem;
/* 順序棧
棧頂指針(top)棧底指針(base)
後進先出(last in first out)LIFO
*/
typedef struct {
elem *top;
elem *base;
int stacksize;
}SqStack;
status initStack(SqStack * stack)
{
stack->base = (elem *)malloc(INIT_SIZE * sizeof(elem));
if(!stack->base) exit(-2);
stack->top = stack->base;
stack->stacksize = INIT_SIZE;
printf("STACK---INIT---SUCCESS\n\n");
return 1;
}
int isStackEmpty(SqStack *stack)
{
if(stack->top == stack->base) return 1;
return 0;
}
status pushStack(SqStack *stack, elem e)
{
if(stack->top - stack->base >= stack->stacksize){
stack->base = (elem *)realloc(stack->base ,(stack->stacksize + INCRE_SIZE) * sizeof(elem));
if(!stack->base) exit(-2);
printf("STACK---PUSH---SUCCESS\n\n");
stack->top = stack->base + stack->stacksize;
stack->stacksize += INCRE_SIZE;
}
*stack->top++ = e;
return 1;
}
status getTop(SqStack *stack, elem *e)
{
if(stack->top == stack->base){
printf("空棧");
return 0;
}
//改變e的值
*e = *(stack->top-1);
//返回棧頂元素
return 1;
}
//pop刪除S的棧頂元素,並用e放回其值
status popStack(SqStack *stack, elem * e)
{
if(!isStackEmpty(stack)){
*e = *(--stack->top);
}
return 1;
}
//返回棧的長度
status getlength(SqStack *stack)
{
return stack->top - stack->base;
}
status clearStack(SqStack *stack)
{
stack->top = stack->base;
return 1;
}
//銷燬棧
status destoryStack(SqStack *stack)
{
if(!stack->base)
free(stack->base);
return 1;
}
//對每一個站內元素調用一個函數
status stackTraverse(SqStack *stack, void visit())
{
if(!isStackEmpty(stack)){
elem *traver = stack->top;
while(stack->base == stack->top--){
visit(*stack->top);
}
stack->top = stack->base + getlength(stack);
}
return 1;
}
int main(int argc, char *argv[]) {
SqStack stack;
initStack(&stack); //初始化棧
for(int i = 0; i < 101; i++){
pushStack(&stack, i); //入棧
}
printf("length = %d\n", getlength(&stack));
for(int j = 0; j < 101; j++){
int e;
popStack(&stack, &e); //出棧
printf("%d\t", e);
}
printf("\n");
if(isStackEmpty(&stack))
printf("Stack Empty!\n");
else
printf("Stack is not Empty!\n");
printf("length = %d\n", getlength(&stack));
clearStack(&stack); //清空棧
// destoryStack(&stack);
return 0;
}