您的位置:首页 > 其它

顺序栈的一般操作

2014-03-11 22:28 239 查看
#include <stdio.h>
//define the size of array
#define MAXSIZE 100
//define new data type: stack
struct stack{
int data[MAXSIZE];
int top;
};
//defint var seqStack
typedef struct stack seqStack;

//create a stack
int create_stack(seqStack* S){
//initial the top to 0
S->top = 0;
printf("create stack comlete!\n");
return 0;
}

int push_stack(seqStack* S, int element){
//is overflow?
if(S->top > 100)
return -1;
//data[top] = element, at the beginning data[0] = element
S->data[S->top] = element;
//top + 1, point to a new empty position
S->top++;
printf("push %d into stack comlete!\n", element);
return 0;
}

//print every element of the stack
int show_stack(seqStack S){
int i;
//top point to the new empty position, so use top-1
for(i=(S.top-1); i>=0; i--){
printf("%d\n",S.data[i]);
}
printf("show stack from top to bottom comlete!\n");
return 0;
}

//print the top element and top-1
int pop_stack(seqStack* S){
//is stack empty
if (S->top == 0) {
printf("the stack is empty!\n");
return 0;
}
//good: --(S->top) will modify the value of top directly
printf("%d\n", S->data[--(S->top)]);
printf("pop stack from top complete!\n");
return 0;
}

int main(){
seqStack S;
//create stack by seqstack address
create_stack(&S);
//push 15 into stack
push_stack(&S, 15);
//push 27 into stack
push_stack(&S, 27);
//push 89 into stack
push_stack(&S, 89);
//print stack from top to bottom
show_stack(S);
//return 89
pop_stack(&S);
//return 27
pop_stack(&S);
//return 15
pop_stack(&S);
//stack already empty, so return
pop_stack(&S);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: