C language uses static arrays to simulate the stack structure
Stack is an important existence in the data structure. This is an advanced post-release structure, just like a "Dead End. Today, we first use the simplest static array method to simulate the stack. Upload the code to https://github.com/chenyufeng1991/stack_staticarray.
(1) Declare the stack size, array, and a stack top pointer. The stack top pointer can retrieve the data at the top of the stack.
#define STACK_SIZE 50static int stack[STACK_SIZE];static int top_element = -1;
(2) When the stack is not full, you can press the element into the top of the stack.
// Press the element void push (int value) {if (! IsFull () {stack [++ top_element] = value ;}}
(3) The top element of the stack is displayed when the stack is not empty. Pointer down, stack element-1.
// The pop-up element void pop () {if (! IsEmpty () {top_element --;}}
(4) take the top element. Note that it is different from the pop-up element in (3. Taking the top element does not change the stack structure.
// Retrieve the top element int top () {if (! IsEmpty () {return stack [top_element];} return-32768 ;}
(5) judge whether the stack is empty and directly judge based on the top pointer of the stack.
// Determine whether the stack is empty. int isEmpty () {return top_element =-1 ;}
(6) Determine whether the stack is full
// Judge whether the stack is full int isFull () {return top_element = STACK_SIZE-1 ;}
(7) print stack elements, which can only be printed from the top
// Print the stack element void printStack () {int I = top_element; printf ("% s function execution, print the value in the static array Stack: \ n ", __function _); if (I =-1) {printf ("This is an empty stack \ n");} else {while (I! =-1) {printf ("% d", stack [I --]);} printf ("\ n ");}}
(8) test code
Int main (int argc, const char * argv []) {push (4); push (6); push (1); push (9); push (2 ); push (8); printStack (); printf ("\ n"); pop (); printf ("the elements of the pop Stack are \ n"); printStack (); printf ("\ n"); printf ("top element value: % d \ n ", top (); return 0 ;}