一,顺序栈的静态分配
二,顺序栈的动态分配
#include<stdio.h>
#include<stdlib.h>
#define initsize 5
#define incresize 5typedef struct Sqstack{int *base;int *top;int stacksize;
}Sqstack;void InitStack(Sqstack *s){(*s).base=(int *)malloc(initsize*sizeof(int));if(!(*s).base)exit(0);(*s).top=(*s).base;(*s).stacksize=initsize;
}
void Push(Sqstack *s,int e){if((*s).top-(*s).base >= (*s).stacksize){(*s).base=(int*)realloc((*s).base,((*s).stacksize+incresize)*sizeof(int));if(!(*s).base)exit(0);(*s).top=(*s).base+(*s).stacksize;(*s).stacksize+=incresize;}*((*s).top)=e;(*s).top++;
}
void GetTop(Sqstack s,int *e){if(s.top==s.base) printf("empty!");*e=*(s.top-1);}
int StackLength(Sqstack s){return s.top-s.base;
}
int StackEmpty(Sqstack s){return (s.top==s.base);
}
void Pop(Sqstack *s,int *e){if((*s).top==(*s).base) exit(0);(*s).top--;*e=*((*s).top);
}
void Destroystack(Sqstack *s){if(s!=NULL){free((*s).base);(*s).base=NULL; (*s).top=NULL;(*s).stacksize=0;}
}int main(){Sqstack s;InitStack(&s);int e,p,x;for(int j=0;j<s.stacksize;j++){scanf("%d",&e);Push(&s,e);}GetTop(s,&p);printf("栈顶元素是%d ",p);if(StackEmpty(s)) printf("\n非空!");else ("\n empty!");int length=StackLength(s);printf("\n 栈长为%d",length);Pop(&s,&x);printf("\n 出栈元素是 %d",x);Destroystack(&s);return 0;
}
三,栈链
#include<stdio.h>
#include<stdlib.h>typedef struct stacknode{int data;struct stacknode *next;
}stackNode,*Linkstack;void Initstack(Linkstack *s){*s=(Linkstack)malloc(sizeof(stackNode));(*s)->next=NULL;}
void Push(Linkstack s,int x){Linkstack p=(Linkstack)malloc(sizeof(stackNode));if(!p)exit(0);p->data=x;p->next=s->next;s->next=p;}
void Gettop(Linkstack s,int *e){if(s->next==NULL)exit(0);*e=s->next->data;
}
int Empty(Linkstack s){return (s->next==NULL);
}void Pop(Linkstack s,int *e){if(s->next==NULL){printf("空!");exit(0);}stackNode *p=s->next;e=p->data;s->next=p->next;free(p);
}
void Destroystack(Linkstack s){Linkstack p=s->next,q;while(p!=NULL){q=p->next;free(p);p=q;}free(s);
}
int main(){Linkstack s;Initstack(&s);int n,x;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&x);Push(&s,x);}Gettop(&s,&x);printf("栈顶元素是 %d\n",x);int flag=Empty(s);if(flag==0)printf("空!");else printf("非空!");Pop(&s,&x);printf("出栈元素是 %d",x);Destroystack(&s);return 0;
}
四,进制转换
五,表达式求值
六,括号的匹配问题
七,迷宫问题