#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<cstdlib> using namespace std; #define LL long long #define M(a,b) memset(a,b,sizeof(a)) typedef struct { int *base;///stack bottom int *top; ///Top of stack int stacksize; } Sqstack; int Initsatck( Sqstack &S) ///Create an empty stack { S.base = (int *)malloc(100*sizeof(int)); ///Apply for space if(!S.base)///Apply for space failed { return -1; } S.top = S.base; S.stacksize = 100;///The initial size of the stack is 100 return 1; } int Destroystack(Sqstack &S)///Destroy the stack { S.top = NULL; S.stacksize = 0; free(S.base); return 1; } int clearstack(Sqstack &S)///Please empty the stack { S.top=S.base; return 1; } int Stackempty(Sqstack &S)///Determine whether the stack is empty { if(S.top == S.base) { return -1; } else { return 1; } } int Stacklen(Sqstack &S)///Get the length of the stack { if(S.top == S.base) { return 0; } else { return (S.top - S.base); } } int Gettop(Sqstack &S)///Get the top element of the stack { you are; if(S.top ==S.base) { return -1; } else { e = * (S.top-1); } return e; } int Push(Sqstack &S,int &e)///Element e is pushed onto the stack { if(S.top - S.base >=100)///Insufficient space { S.base = (int*)realloc(S.base,(S.stacksize + 10)*sizeof(int)); if(!S.base) { return -1; } S.top = S.base +100; S.stacksize +=10; } *S.top = e;///Such as stack operation S.top++; return 1; } int Pop(Sqstack &S, int &e)///The top element of the stack is popped, and e returns its value { if(S.top == S.base) { return -1; } else { S.top--; e = * S.top; return e; } } int Stacktraverse(Sqstack &S)///Traverse and output the stack elements { if(S.base == NULL) { return -1; } int *p; p = S.base; while(p<S.top) { printf("%d ",*p); p++; } printf("\n"); return 1; } intmain() { int n; int num[1005]; int num2[1005]; Sqstack S; initsatck(S); if(Stackempty(S)) { printf("This stack is empty\n\n\n"); } printf("Please enter the number of elements in the stack\n"); while(~scanf("%d",&n)) { printf("Please enter the stack element:\n"); for(int i=0; i<n; i++) { scanf("%d",&num[i]); Push(S,num[i]); } int del, e2; printf("Please enter the value and position of the element you want to insert\n"); scanf("%d %d",&del,&e2); for(int i=0; i<n-del+1; i++) { num2[i]=Pop(S,num2[i]); } Push(S,e2); Stacktraverse(S); for(int i=n-del; i>=0; i--) { Push(S,num2[i]); } printf("The element in the stack after insertion is\n"); Stacktraverse(S); printf("Please enter the position to delete the element:\n"); int del2; scanf("%d",del2); M (num 2.0); for(int i=0; i<n-del+2; i++) { num2[i]=Pop(S,num2[i]); } printf("The removed element is: "); printf("%d\n",num2[n-del-1]); for(int i=n-del; i>=0; i--) { Push(S,num2[i]); } printf("The element in the stack after deleting the element is:\n"); Stacktraverse(S); } return 0; }
Running the graph: