The stack is an important data structure with different implementations, and the program demonstrates how to implement simple stack operations with arrays.
To define a header file:
1#include <stdio.h>2#include <stdlib.h>3 #defineMax_size 104 intStack[max_size];5 inttop=-1; 6 7 voidPushintelement);8 intpop ();9 intisEmpty ();Ten intisfull (); One voidstackfull (); A voidstackempty (); - voidPrintintStack[]);
Into the stack operation:
1 void push (int element) {2 if(Isfull ()) {3 4 5 stack[++top]=6 }
The stack operation:
1 int pop () {2 if (IsEmpty ()) {3 4 }5 return stack[top--6
Determine if the stack is full:
1 int Isfull () {2 if (top==max_size-1) 3 return 1 ; 4 return 0 5 }
Determine if the stack is empty:
1 int IsEmpty () {2 if (top<0) 3 return 1 ; 4 return 0 ; 5
Is the operation when the stack is full and the stack is empty:
1 voidStackfull () {2fprintf (stderr,"stack is full,cannot push more!"); 3 exit (exit_failure);4 } 5 voidStackempty () {6fprintf (stderr,"Stack is empty,cannot pop more!"); 7 exit (exit_failure);8}
Print all the stack elements (the elements in all stacks will not exist after printing!) ):
1 void print (int stack[]) {2while (! IsEmpty ()) {3 printf ("%4d", Pop ()); 4 5
Main function test:
1 intMainvoid)2 {3 inti;4 for(i=0;i<Ten; i++){ 5Push (i+1);6 }7 pop ();8 pop ();9 print (stack);Ten pop (); One return 0; A}
Array implementation Stack