C栈-顺序表实现

#include <stdio.h>
#include <stdlib.h>
#define INITIAL_SIZE 10

struct stack{
int *top;
int *base;
int stackSize;
};

typedef struct stack * Stack;

void initial(Stack stack){ 
  stack->stackSize = INITIAL_SIZE;
  stack->base = stack->top = (int*)malloc(INITIAL_SIZE*sizeof(int));
}

int getTop(Stack stack){
if(stack->base == stack->top){return NULL;}
int* p = stack->top;
p--;
return *p;
}

int pop(Stack stack ){
   if(stack->base == stack->top){return NULL;}
int* p = stack->top;
p--;
stack->top = p;
return *p;
}

void push(Stack stack , int data){
if((stack->top-stack->base)>=stack->stackSize){return;}
*(stack->top)=data;
stack->top++;
}

int getLength(Stack stack){
   return stack->top-stack->base;
}

void iteratorElem(Stack stack){
printf("\n======================================\n");
int * p = stack->base;

while(p != stack->top){
printf("%d  \t",*p);
p++;
}
printf("\n======================================\n");

}

void main(){

Stack stack=(Stack)malloc(sizeof(Stack));
initial(stack);
int num = 0;
for(int i =0;i<8;i++){
scanf("%d",&num);
push(stack,num);
}
     iteratorElem(stack);
printf("Stack top elem: %d\n",getTop(stack));
printf("Stack elem length: %d\n",getLength(stack));
for(i =0;i<8;i++){
pop(stack);
iteratorElem(stack);
printf("Stack top elem: %d\n",getTop(stack));
printf("Stack elem length: %d\n",getLength(stack));
}
}

你可能感兴趣的:(C++,c,C#)