顺序栈是利用一组地址连续的存储单元依次存放自栈低到栈顶的数据元素,利用指针top、bottom指示栈顶和栈底元素在顺序栈中的位置。
实现方式:先为栈分配一个合理的栈容量、在使用的过程中当栈的空间不够用时再逐段扩大。
代码实现:
//2015.01.08 顺序栈的实现 #include "iostream" using namespace std; #include "malloc.h" #define TYPE int #define INCREMENT_SIZE 4 typedef struct _Stack { unsigned int size; TYPE* top; TYPE* bottom; }Stack; void init_stack(Stack* stack); void push(Stack* stack,TYPE val); TYPE pop(Stack* stack); void traverse(Stack* stack); int main(void) { Stack stack; init_stack(&stack); push(&stack,1); push(&stack,2); push(&stack,3); push(&stack,4); push(&stack,5); push(&stack,6); push(&stack,7); push(&stack,8); //cout<<pop(&stack)<<endl; //cout<<pop(&stack)<<endl; //cout<<pop(&stack)<<endl; //cout<<pop(&stack)<<endl; traverse(&stack); return 0; } //初始化栈 void init_stack(Stack* stack) { stack->size = INCREMENT_SIZE; stack->top = stack->bottom = new TYPE[INCREMENT_SIZE]; if(NULL == stack->top) { exit(-1); } } //压栈 void push(Stack* stack,TYPE val) { int i = stack->top-stack->bottom; if(stack->top-stack->bottom >=stack->size) //判断是否扩展栈的容量 { int new_size = stack->size+ INCREMENT_SIZE; //栈新的容量大小 stack->bottom = (TYPE*)realloc(stack->bottom ,new_size*sizeof(TYPE));//为新栈分配内存空间并将原栈中内容拷到新的栈中 if(NULL == stack->bottom) { exit(-1); } stack->top = stack->bottom + stack->size; stack->size = new_size; *(stack->top++) = val; } else { *(stack->top++) = val; } } //出栈 TYPE pop(Stack* stack) { TYPE val; if(stack->top == stack->bottom) { cout<<"栈为空,出栈失败"<<endl; exit(-1); } else { val = *(--stack->top); return val; } } //遍历栈 void traverse(Stack* stack) { if(stack->top == stack->bottom) { cout<<"栈为空,遍历栈失败"<<endl; } else { while(stack->top != stack->bottom) { cout<<*(--stack->top)<<endl; } } }