簡單棧的c語言實現

#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.插入學生\n 2.刪除最後一個學生並輸出\n 3.輸出棧的長度\n 4.銷燬棧\n 5.清空棧 \n 6.查詢該棧是否爲空 \n 7.輸出最後一個學生\n 8.輸出整個棧中的所有學生\n 9.建立棧(在銷燬後重建)\n");

scanf("%d",&set);

switch(set){

case 1:printf("請輸入學生的姓名和分數,用空格分隔\n");scanf("%s %d",student_in.name,&student_in.score);if(Push(s,student_in)) printf("插入成功\n");;break;

case 2:if(Pop(s,student_top))printf("%s,%d\n",student_top.name,student_top.score);else printf("棧裏無學生\n");break;

case 3:printf("%d\n",StackLength(s));break;

case 4:if(DestoryStack(s)) printf("銷燬成功\n");break;

case 5:if(ClearStack(s)) printf("清空成功\n");break;

case 6:if(IsStackEmpty(s)) printf("棧爲空\n"); else printf("棧不爲空\n");break;

case 7:if(GetTop(s,student_top))printf("%s,%d\n",student_top.name,student_top.score);else printf("棧裏無學生\n");break;

case 8:PrintStack(s);break;

case 9:InintStack(s);break;

}

printf("結束輸入0\n");

scanf("%d",&isclose);

if(!isclose) break;

}

return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章