#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define Stackincrement 10
typedef struct{
Char name[10];
int score;
}student;
typedef struct {
Student *base;
Student *top;
int stacksize;
}sqstack;
Sqstack Inintstack (Sqstack &s) {
s.base= (Student *) malloc (stack_init_size *sizeof (student));
if (! S.base) exit (1);
S.top=s.base;
S.stacksize=stack_init_size;
printf ("Bulid succeed\n");
return S;
}
BOOL Clearstack (Sqstack &s) {
/*while (s.top) {
S.top=null;
s.top--;
if (s.top==s.base)
S.top=s.base=null;
}*/
S.top=s.base;
return true;
}
BOOL Destorystack (Sqstack &s) {
Free (s.base);
return true;
}
BOOL Isstackempty (Sqstack &s) {
if (s.top==s.base)
return true;
Else
return false;
}
int Stacklength (Sqstack &s) {
return (s.top-s.base);
}
BOOL GetTop (Sqstack &s,student &e) {
if (s.top==s.base) {
return false;
}
e=* (s.top-1);
return true;
}
BOOL Push (Sqstack &s,student e) {
printf ("%d\n", E.score);
if (s.top-s.base>=s.stacksize) {
s.base= (Student *) realloc (s.base, (s.stacksize+stackincrement) *sizeof (student));
if (! S.base) exit (1);
S.top=s.base+s.stacksize;
S.stacksize+=stackincrement;
}
* S.TOP=E;
s.top++;
return true;
}
BOOL Pop (Sqstack &s,student &e) {
if (s.top==s.base) return false;
E=*--s.top;
return true;
}
BOOL Printstack (Sqstack &s) {
int i=0;
while ((s.top-i)!=s.base) {
i++;
printf ("%s,%d\n", (* (S.top-i)). Name, (* (S.top-i)). Score);
}
return true;
}
int main () {
Sqstack s;
Inintstack (s);
int set,isclose;
Student Student_in,student_top;
/*student STUDENT[10];
for (int i=0;i<2;i++) {
scanf ("%s%d", student[i].name,&student[i].score);
Push (S,student[i]);
}
Printstack (s);
*/
while (1) {
set=0;
printf ("1." Insert student \ n 2. Delete the last student and Output \ n 3. The length of the output stack \ n 4. Destroy stack \ n 5. Empty stack \ n 6. Output the last student \ n 7. Outputs all students in the stack \ n 8. Build stack (rebuild after destruction) \ n " );
scanf ("%d", &set);
Switch (SET) {
Case 1:printf ("Please enter the student's name and score, separated by a space \ n"), scanf ("%s%d", student_in.name,&student_in.score); if (Push (s,student_in)) printf ("Insert succeeded \ n");; Break
Case 2:if (Pop (s,student_top)) printf ("%s,%d\n", Student_top.name,student_top.score), Else printf ("No students in the stack \");
Case 3:printf ("%d\n", Stacklength (s));
Case 4:if (Destorystack (s)) printf ("Destroy succeeded \ n");
Case 5:if (Clearstack (s)) printf ("Empty succeeded \ n");
Case 6:if (Isstackempty (s)) printf ("Stack is empty \ n"); else printf ("stack is not empty \ n");
Case 7:if (GetTop (s,student_top)) printf ("%s,%d\n", Student_top.name,student_top.score), Else printf ("No students in the stack \ \"); Break
Case 8:printstack (s);
Case 9:inintstack (s);
}
printf ("End input 0\n");
scanf ("%d", &isclose);
if (!isclose) break;
}
return 0;
}
This article from "zjwzjw369" blog, declined reprint!
C language implementation of simple stacks