I am in front of a blog "C language implementation using static arrays to construct stack structure" uses static arrays to simulate stack operations. The size of a static array is written in code and is stored on the user stack, and is not flexible to use. In this blog I will use a dynamic array to construct, the memory used at this time is dynamically applied, but there is a difference between the creation and release of the array, and other uses are the same. Note: Dynamically requested memory is required to be released manually, because the memory consumed is on the runtime heap and will not be released after the program exits. and stored on the stack will be automatically released after the program exits. Code uploaded to Https://github.com/chenyufeng1991/Stack_DynamicArray.
(1) Creating stacks
Create the stack, which is the array allocation
void Createstack (int size) {
if (staticsize = = 0) {
staticsize = size;
stack = (int *) malloc (staticsize * sizeof (int));
if (stack = = NULL) {
printf ("Array memory allocation failed \ n");}}
(2) Destroy stack
Destroy this stack, focusing on freeing the stack of memory
void Destroystack () {
if (staticsize > 0) {
staticsize = 0;
Free (stack);
stack = null;//array null
top_element = -1;//pointer null
}
}
(3) Other basic operations
Pressed element
void push (int value) {
if (!isfull ()) {
stack[++top_element] = value;
}
}
Pop-up element
void Pop () {
if (!isempty ()) {
top_element--
}
}
Take top element
int () {
if (!isempty ()) {return
stack[top_element];
return-32768;
}
null
int IsEmpty () {return
top_element = = 1;
}
Full
int isfull () {return
top_element = = staticSize-1;
}
Print element
void Printstack () {
int i = Top_element from the top of the stack;
printf ("Print out the value inside the dynamic array stack:");
if (i = = 1) {
printf ("This is an empty stack");
} else{
while (i!=-1) {
printf ("%d", stack[i--]);
}
printf ("\ n");
}
(4) Test code
int main (int argc, const char * argv[]) {
createstack (m);
Printstack ();
Push (6);p Ush (3);p Ush (9);p Ush (1);p Ush (4);
printf ("After data is pressed in the stack: \ n");
Printstack ();
Pop ();p op ();
printf ("After the data is ejected, the elements within the stack are: \ n");
Printstack ();
printf ("The element on top of the stack:%d\n", tops ());
Destroystack ();
Printstack ();
return 0;
}