top存储堆栈顶部元素的下标值。开始由于没有顶部元素,网站空间,香港虚拟主机,所以初始值为-1,提示堆栈为空。
pop函数不需要从数组中删除元素,只减少顶部元素的下标值就足矣。
3、现在测试一下上面的堆栈的正确性(在上面的代码文件中,添加如下代码)。
void print_stack(){int i = top;for(; i >= 0; i–){printf(, stack[i]);}printf();printf(, get_top());}int main() {char c;scanf(, &c);){)push(&c);scanf(, &c);}printf();print_stack();printf();printf();pop();print_stack();printf();return 0;}
打印结果如下:
动态数组堆栈
动态数组的特点:运行时才决定数组大小。——故需在原有的操作上,添加几个操作。
1、先把你要做的事情准备好。
*stack;int stack_size;int top = -1; create_stack(){}void destroy_stack(){}void push(){}void pop(){}char get_top(){}int is_empty(){}int is_full(){}
2、开始逐步实现每一个函数。
#include <stdio.h>#include <assert.h>#include <malloc.h>*stack;int stack_size;int top = -1;create_stack(int size){assert(size > 0);stack_size = size;stack = (char *)malloc(stack_size * sizeof(char));assert(stack != NULL);}void destroy_stack(){assert(stack_size > 0);free(stack);stack_size = 0;stack = NULL;}void push(char *value){assert(!is_full());stack[++top] = *value;}void pop(){assert(!is_empty());–top;}char get_top(){assert(!is_empty());return stack[top];}int is_empty(){assert(stack_size > 0);return top == -1;}int is_full(){assert(stack_size > 0);return top == stack_size – 1;}
3、现在测试一下上面的堆栈的正确性(在上面的代码文件中,服务器空间,添加如下代码)。
void print_stack(){int i = top;for(; i >= 0; i–){printf(, stack[i]);}printf();printf(, get_top());}int main() {char c;create_stack(100);scanf(, &c);){)push(&c);scanf(, &c);}printf();print_stack();printf();printf();pop();print_stack();printf();destroy_stack();return 0;}
打印结果如下:
我等你用尽了所有的哀伤;而你眼中却有我所不懂的凄凉。