#include <stdio.h>#include<stdlib.h>#include<malloc.h>//Defining Nodesstructnode{intdata; structNode *next;}; typedef Node Stacknode;//Defining Stacks structstack{Stacknode*top; Stacknode*Base;}; typedef Stack Sqstack; //define a function to create a stack intInitstack (Sqstack *s) {s-Base= (stacknode*) malloc (sizeof(Node)); if(! S->Base) {printf ("Error"); Exit (1); } S->top = s->Base; return 0; } //defining a stack function intPushstack (Sqstack *S) {inte; Stacknode*PS; PS= (Stacknode *) malloc (sizeof(Node)); if(!PS) {printf ("Error"); Exit (1); } printf ("Please enter the number you need to press into the stack:"); scanf_s ("%d", &e); PS->data =e; PS->next = s->top; S->top =PS; return 0; } //defining the Stack function intPopstack (Sqstack *S) {inte; Stacknode*PS; PS= s->top; S->top = s->top->Next; E= ps->data; Free (PS); returne;} //defining stack Traversal functions intTravelstack (Sqstack *S) {Stacknode*PS; PS= s->top; while(PS! = s->Base) {printf ("data are:%d\n", ps->data); PS= ps->Next; } return 0; } //defines whether the stack is an empty function BOOLEmptystack (Sqstack *S) {Stacknode*PS; PS= s->top; if(PS = = s->Base) { return true; } Else { return false; } } //define a function to empty the stack intClearstack (Sqstack *S) {Stacknode*PS; PS= s->top; while(S->top! = s->Base) {S->top = s->top->Next; Free (PS); } return 0; } //Main function intMain () {intI,dec,input,dec; Sqstack*Stack; Stack=NewStack; Initstack (stack); Do{printf ("Please select the basic action you need: \ n"); printf ("1************ Adding data to the stack \ n"); printf ("2************ traverse the stack \ n"); printf ("3************ empty the stack \ n"); printf ("4************ Delete stack top element \ n"); scanf_s ("%d", &i); Switch(i) { Case 1: {printf ("do you want to enter data into the stack? Yes Select 1/no select 2\t"); scanf_s ("%d", &Dec); while(Dec = =1) {pushstack (stack); printf ("do you want to continue entering data? Yes Select 1/no select 2\t"); scanf_s ("%d", &input); Dec=input; } printf ("The data you entered is: \ n"); Travelstack (stack); Break; } Case 2: {travelstack (stack); Break; } Case 3: {clearstack (stack); if(Emptystack (Stack)) {printf ("the stack is empty! "); } Else{printf ("the stack is not empty! "); }; Break; } Case 4: { intReturndata; Returndata=popstack (stack); Break; }} printf ("do you want to continue? Yes Select 1/no select 2:\t"); scanf_s ("%d", &DEC); } while(DEC = =1); }
Basic operation of the "data structure" C language stack