data structure of the stack (C language Implementation)
1. Stack model
Stacks are tables that restrict insertions and deletions to only one location, which is the end of the table, called the top of the stack. The basic operation of the stack is push (stack) and pop (out of stack), which is equivalent to insert, the latter is to delete the last inserted element. The last inserted element can be examined before performing a pop by using the top routine. A pop or top on an empty stack is generally considered a stack ADT error. On the other hand, when running push, space exhaustion is an implementation error, but not a ADT error.
2. Stack array implementation stack.h file
#ifndef _stack_h_
#define _STACK_H_
#define Emptytos -1 //empty stack
#define MINSTACKSIZE 5 // The minimum value of the stack is
typedef int ElementType; Data type
typedef struct STACKRECORD
{
int capacity;//capacity
int stacktop;//stack top
elementtype *array ;
} STACK;
int IsEmpty (STACK *s); null
int isfull (STACK *s); Full
STACK *createstack (int maxelements); The creation of the stack
void Disposestack (Stack *s); The release of the Stack
void Makeempty (Stack *s); Create empty stack
void push (elementtype element, stack *s);//into Stack
elementtype top (stack *s); Returns the stack top element
void pop (stack *s); Out Stack
elementtype topandtop (Stack *s); Stack and return the top element of the stack
#endif
Stack.c
#include <stdlib.h> #include <stdio.h> #include "stack.h" int isempty (stack *s) {return (s->stacktop
= = Emptytos);
int Isfull (STACK *s) {return (S->stacktop = = s->capacity-1);}
Stack *createstack (int maxelements) {stack *s;
if (Maxelements < minstacksize) {printf ("Stack size si too small\n");
return NULL;
} s = (STACK *) malloc (sizeof (struct stackrecord));
S->array = (ElementType *) malloc (sizeof (elementtype) * maxelements);
s->capacity = maxelements;
Makeempty (s);
return s;
} void Disposestack (STACK *s) {if (S!= NULL) {free (S->array);
Free (s);
} void Makeempty (STACK *s) {if (S!= NULL) {s->stacktop = Emptytos;
} void push (ElementType element, STACK *s) {if (!isfull (s)) {s->stacktop++;
S->array[s->stacktop] = element;
else {printf ("full stack\n");
}} ElementType Top (STACK *s) { if (!isempty (s)) {return s->array[s->stacktop];
else {printf ("Empty stack\n");
return 0;
} void Pop (STACK *s) {if (!isempty (s)) s->stacktop--;
else printf ("Empty stack\n");
} ElementType topandtop (STACK *s) {if (!isempty (s)) {return s->array[s->stacktop--];
else {printf ("Empty stack\n");
return 0; }
}