动态栈Stack的C语言实现
生活随笔
收集整理的這篇文章主要介紹了
动态栈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 elementStackNode *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; }?
?
?
轉載于:https://www.cnblogs.com/gentlecoding/archive/2012/11/29/3589405.html
總結
以上是生活随笔為你收集整理的动态栈Stack的C语言实现的全部內容,希望文章能夠幫你解決所遇到的問題。