动态栈Stack的C语言实现
前段时间实现了单双向链表以及查找二叉树,今天花了点时间写了下动态栈的实现。初学,代码比较粗糙,望指点。
#include <stdio.h> #include <stdlib.h> struct StackNode{ int data; StackNode *next; }; struct MyStack{ bool IsEmpty; bool IsFull; int size; StackNode *top; }; MyStack *initStack(void){ struct MyStack *p; p=NULL; p=(MyStack *)malloc(sizeof(MyStack)); if(p==NULL){printf("InitError\n");exit(-1);} p->IsEmpty=true; p->IsFull=false; p->size=0; p->top=NULL; return p; } void push(int data,MyStack *s){ MyStack *t=s; //New stack.There is no element StackNode *sn=NULL; sn=(StackNode *)malloc(sizeof(StackNode)); sn->data=data; sn->next=t->top; t->top=sn; t->size+=1; if(t->IsEmpty)t->IsEmpty=false; printf("Success!\n"); return ; } int pop(MyStack *s,int num){ if(s==NULL){printf("pop error: stack is NULL \n");return -1;} if(s->IsEmpty){printf("pop error: stack is empty \n");return -1;} if(s->size<num){printf("pop error: stack elements are not enough to pop out \n");return -1;} int i=0; if(num==s->size){s->IsEmpty=true;} printf("POP : \n"); int returnNum; for(;i<num;i++){ printf("%4d : %d \n",i+1,s->top->data); returnNum=s->top->data; StackNode *stacktofree = s->top; s->top=s->top->next; free(stacktofree); s->size-=1; } printf("%d elements remain\n",s->size); printf("Success!\n"); return returnNum; // NOTE: ONLY RETURN THE TOP ELEMENT } void traversal(MyStack *s){ MyStack *t=s; StackNode *sn=t->top; printf("TRAVERSAL (Total size : %d)\n",t->size); if(sn==NULL){printf("There is no element left \n");return;} while(sn!=NULL){ printf( " * %d\n",sn->data); sn=sn->next; } printf("Success!\n"); return; } void welcomeInfo(){ printf("*********************************************************************\n"); printf("*Input format : [I DATA][O DATA][T] *\n"); printf("*Input operation : I = PUST O = POP T=Traversal *\n"); printf("*********************************************************************\n"); } int main(){ MyStack *s =initStack(); char op; int data; welcomeInfo(); while(1){ scanf_s("%c",&op,1); switch (op) { case 'I':{ scanf_s("%d",&data); push(data,s); welcomeInfo(); getchar(); break; } case 'O':{ scanf_s("%d",&data); pop(s,data); welcomeInfo(); getchar(); break; } case 'T':{ traversal(s); welcomeInfo(); getchar(); break; } default:{printf("Wrong syntax!\n");getchar();break;} } } system("pause"); return 0; }