/*
順序棧
VS2010 調試
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
#define STACKINCREASEMENT 10
struct SeqStack
{
int *elem;
int top;
int MAXNUM;
};
//初始化棧
int init_seq_stack(struct SeqStack *L)
{
L->elem = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
if (!L->elem)
{
return 0;
}
L->top = 0;
L->MAXNUM = STACK_INIT_SIZE;
return 1;
}
/*
函數功能: 判斷是否棧滿
返 回 值: 0 棧滿; 1 棧未滿
*/
int is_stack_full(struct SeqStack L)
{
return (L.top == L.MAXNUM);
}
/*
函數功能: 判斷是否棧空
返 回 值: 0 棧空; 1 棧未空
*/
int is_stack_empty(struct SeqStack L)
{
if (L.top == 0)
{
return 0;
}
else
{
return 1;
}
}
/*
函數功能: 數num 進棧
返 回 值: 0 進棧失敗; 1 進棧成功
*/
int push_stack(struct SeqStack *L, int num)
{
if (is_stack_full(*L))
{
return 0;
}
L->top++;
L->elem[L->top] = num;
return 1;
}
/*
函數功能: 出棧,出棧的數存到x內
返 回 值: 0 失敗; 1 成功
*/
int pop_stack(struct SeqStack *L, int *x)
{
if (!is_stack_empty(*L))
{
return 0;
}
*x = L->elem[L->top];
L->top = L->top - 1;
return 1;
}
/*
函數功能: 取棧頂元素
返 回 值: 棧頂元素值
*/
int get_top_elem(struct SeqStack L)
{
return L.elem[L.top];
}
/*
函數功能: 打印棧內元素
*/
void print_stack_elem(struct SeqStack L)
{
int i = 0;
printf("TOP\n");
for(i = L.top; i > 0; i--)
{
printf("%d\n", L.elem[i]);
}
printf("BOTTOM\n");
printf("\n");
}
/*
函數功能: 將棧置空
*/
void set_empty(struct SeqStack *L)
{
L->top = 0;
}
/*
函數功能: 銷燬棧
*/
int destory_stack(struct SeqStack *L)
{
if (!L->elem)
{
return 0;
}
free(L->elem);
return 1;
}
int main(int argc, char *argv[])
{
int x = 0;
struct SeqStack L;
init_seq_stack(&L);
push_stack(&L, 7);
push_stack(&L, 4);
push_stack(&L, 5);
push_stack(&L, 8);
push_stack(&L, 9);
print_stack_elem(L);
pop_stack(&L, &x);
print_stack_elem(L);
destory_stack(&L);
return 0;
}
順序棧的實現(C語言)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.