堆棧 ( stack ),也可直接稱棧。堆棧數據結構只允許在一端進行操作,并按照后進先出( LIFO, Last In First Out )的原理運作。
堆棧數據結構使用兩種基本操作:
壓棧( push ) :將數據放入堆棧的頂端,堆棧頂端指針指標+1。
彈棧( pop ) :將頂端數據資料輸出,堆棧頂端指針指標-1。

/**
* <!--
* File : stack.h
* Author : fancy
* Email : fancydeepin@yeah.net
* Date : 2013-02-03
* --!>
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define Element char
#define INIT_SIZE 10
#define INCREMENT_SIZE INIT_SIZE / 2
typedef struct TStack {
Element *base;
Element *top;
int size;
} *Stack;
//棧的構造器,創建空棧
void stackConstructor(Stack &stack){
stack->base = (Element *)malloc(INIT_SIZE * sizeof(Element));
if(!stack->base){
printf("\n為棧分配內存空間失敗!\n");
exit(0);
}
stack->top = stack->base; //空棧 top == base
stack->size = INIT_SIZE;
}
//是否為空棧
bool isEmpty(Stack stack){
if(stack->top == stack->base){
return true;
}
return false;
}
//壓棧
bool push(Stack &stack, Element e){
if(stack->top - stack->base >= stack->size){ //棧滿
stack->base = (Element *)realloc(stack->base, (stack->size + INCREMENT_SIZE) * sizeof(Element));
if(!stack->base){
printf("\n為棧擴展內存空間失敗!\n");
return false;
}
stack->top = stack->base + stack->size;
stack->size += INCREMENT_SIZE;
}
*stack->top++ = e;
return true;
}
//彈棧
Element pop(Stack stack){
if(isEmpty(stack)){
printf("\n棧為空,彈棧操作失敗!\n");
return ' ';
}
return *--stack->top;
}
/**
* <!--
* File : Stack.cpp
* Author : fancy
* Email : fancydeepin@yeah.net
* Date : 2013-02-03
* --!>
*/
#include "stack.h"
int main() {
Stack stack;
stackConstructor(stack);
push(stack, 'f');
push(stack, 'a');
push(stack, 'n');
push(stack, 'c');
push(stack, 'y');
printf("%c", pop(stack));
printf("%c", pop(stack));
printf("%c", pop(stack));
printf("%c", pop(stack));
printf("%c", pop(stack));
//output[result]: ycnaf
return 0;
}
posted on 2013-02-03 06:40
fancydeepin 閱讀(1569)
評論(0) 編輯 收藏