1. A stack is a data structure first in and then out. Its implementation can be represented by an array or a stack top pointer. When an array is used, a certain size can be pre-allocated to the stack. When the stack is empty, the value of the lower mark is-1. Each time an element is added, the value of the lower mark is added with 1. When the stack is exited, an element is displayed. The value of the lower mark is reduced by 1, to determine whether the stack is empty, you can use the bottom mark value top to determine whether it is-1.
# include
# include
int stack[100]={};int top=-1;int size=100;int main(){void push(int a[],int);int pop(int a[]);int isempty(int a[]);push(stack,1);push(stack,2);push(stack,3);printf("%d\n",isempty(stack));printf("%d\n",pop(stack));printf("%d\n",pop(stack));system("pause");return 0;}void push(int a[],int x){if(top>=size)printf("out of range");elsetop++; stack[top]=x;}int pop(int a[]){if (top==-1){printf("stack is empty");exit(-1);}return a[top--]; }int isempty(int a[]){return top==-1;}
2. The stack can also be implemented using pointers. The defined struct represents a node. Each node contains two elements, one being the data value of the node, and the other being the precursor pointer. The stack inbound operation is
# include
# include
struct node{int num;struct node *next;};typedef struct node *link;int main(){link stack=NULL;link push(link,int);int pop(link);int isempty(link);link s=push(stack,1);s=push(s,2);s=push(s,3);printf("%d\n",pop(s));printf("%d\n",isempty(s));system("pause");return 0;}link push(link stack,int x){link newele=(link)malloc(sizeof(node));if(!newele)exit(-1);newele->next=stack;newele->num=x;stack=newele;return stack;}int pop(link stack){if(!stack)return -1;int t;link temp=stack;stack=stack->next;t=temp->num;free(temp);return t;}int isempty(link stack){return stack==NULL;}
3 stack applications
Stack can be used to convert a decimal number to another hexadecimal number, for example, convert a decimal number to an octal number, N = (N/8) * 8 + N % 8, divide N by 8 and write the commodity value in turn to get the corresponding octal number, which is similar to the stack's nature. The following uses an array to implement a stack, use this stack to implement the hexadecimal number conversion.
# include
# include
int stack[100]={};int top=-1;int size=100;int main(){ int t;void push(int a[],int);int pop(int a[]);int isempty(int a[]);printf("input the decimal number\n"); scanf("%d",&t);if(t>0){while(t){push(stack,t%8);t=t/8;}while(!isempty(stack)){printf("%d",pop(stack));}}else{t=-t;while(t){push(stack,t%8);t=t/8;}printf("-");while(!isempty(stack)){printf("%d",pop(stack));}}printf("\n");system("pause");return 0;}void push(int a[],int x){if(top>=size)printf("out of range");elsetop++; stack[top]=x;}int pop(int a[]){if (top==-1){printf("stack is empty");exit(-1);}return a[top--]; }int isempty(int a[]){return top==-1;}