Implementation of chain stack

#include<stdlib.h>

#include<stdio.h>

#include<malloc.h>

typedef int DataType;

typedef struct node{ struct node *next;//Pointer field DataType data;//Data field}Stack;

void initStack(Stack **head);//Initialization

int isEmpty(Stack *head);//Judgment is not empty or not

int StackPush(Stack *head,DataType x);//入栈

int StackPop(Stack *head,DataType *x);//出栈

int StackGet(Stack *head,DataType *x);//Get the top element of the stack

void Destory(Stack *head);//Undo the stack

int main(void){ int x,i; Stack *stack; initStack(&stack); for(i=0;i<10;i++) StackPush(stack,i+1); for(i=0;i<10;i++) { StackPop(stack,&x); printf("x=%d\n",x); }

isEmpty(stack);
return 0;

}

void initStack(Stack **head){ *head=(Stack *)malloc(sizeof(Stack));//Dynamic application (*head)->next=NULL;//Set the next field of the head pointer to null }

int StackPush(Stack *head,DataType x){ Stack *p; p=(Stack *)malloc(sizeof(Stack)); p->data=x; p->next=head->next; head->next=p; printf("入栈成功\n"); return 0; }

int isEmpty(Stack *head){ Stack *p=head->next; if(p!=NULL){ printf("栈非空\n"); return 1; } printf("栈空\n"); return 0; }

int StackPop(Stack *head,DataType *x){ Stack *p=head->next; if(p==NULL){ printf("链栈已空\n"); return 0; } head->next=p->next; *x=p->data; free(p); printf("出栈成功\n"); return 1; }

int StackGet(Stack *head,DataType *x){ Stack *p; p=head->next; if(p==NULL){ printf("Get the top element of the stack is empty\n"); return 0; }

*x=p->data;
return 1;

}

void Destory(Stack *head){ Stack *p,*q; p=head; while(p!=NULL){ q=p; p=p->next; free(q); } }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325680199&siteId=291194637
Recommended