栈的简单实现

类型是采用INT类型。

代码如下:

const int DATASIZE = 100; typedef struct _stack { int data[DATASIZE]; int top; //栈顶指针 }Stack; //初始化栈 Stack* InitStack() { Stack* pStack = (Stack*)malloc(sizeof(Stack)); if(!pStack) { printf("intilize fail........../n"); return NULL; } else { pStack->top = -1; return pStack; } } //压入数据 Stack* Push(Stack* stack,int newValue) { if(stack == NULL) { printf("stack is null....../n"); return NULL; } else if(stack->top == DATASIZE) { printf("stack is full......./n"); return stack; } else { stack->top++; stack->data[stack->top] = newValue; return stack; } } //弹出数据 int Pop(Stack* stack) { if(stack == NULL) { printf("stack is null....../n"); return 0; } else if(stack->top == -1) { printf("stack is empty......./n"); return 0; } else { stack->top--; return stack->data[stack->top]; } } //获得栈顶元素 int GetTop(Stack* stack) { if(stack == NULL) { printf("stack is null....../n"); return 0; } else { return stack->data[stack->top]; } } //判断栈是否为空 bool EmptyStack(Stack* stack) { if(stack->top == -1) return false; else return true; } //打印栈数据 void Display(Stack* stack) { int len = stack->top; for(int i = 0;i<=len;i++) printf("%d ",stack->data[i]); printf("/n"); } int GetStackSize(Stack* stack) { return stack->top + 1; }

你可能感兴趣的:(struct,null)