贪心Prim算法生成树问题C实现代码
2018-07-20 来源:open-open
#include <stdio.h> #include <stdlib.h> #define STACK_INIT_SIZE 20 #define STACKINCREMENT 10 typedef char ElemType; typedef struct{ ElemType *base; ElemType *top; int stacksize; }sqStack; /*初始化栈*/ void initStack(sqStack *s) { /*内存中开辟一段连续空间作为栈空间,首地址赋值给s->base*/ s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); if(!s->base) exit(0); /*分配空间失败*/ s->top = s->base; /*最开始,栈顶就是栈底*/ s->stacksize = STACK_INIT_SIZE; /*最大容量为STACK_INIT_SIZE */ } /*入栈操作,将e压入栈中*/ void Push(sqStack *s, ElemType e){ if(s->top - s->base >= s->stacksize){ /*栈满,追加空间*/ s->base = (ElemType *)realloc(s->base, (s->stacksize + STACKINCREMENT)*sizeof(ElemType)); if(!s->base) exit(0); /*存储分配失败*/ s->top = s->base + s->stacksize; s->stacksize = s->stacksize + STACKINCREMENT; /*设置栈的最大容量*/ } *(s->top) = e; /*放入数据*/ s->top++; } /*出栈操作,用e将栈顶元素返回*/ void Pop(sqStack *s , ElemType *e){ if(s->top == s->base) return; *e = *--(s->top); } /*计算堆栈s当前的长度*/ int StackLen(sqStack s){ return (s.top - s.base) ; } int match(char e,char c) { if(e=='('&&c==')') return 1; if(e=='['&&c==']') return 1; return 0; } void main() { sqStack s; char c,e; initStack(&s); scanf("%c",&c); while(c!='#') { if(!StackLen(s)) Push(&s,c); else { Pop(&s,&e); if(!match(e,c)) { Push(&s,e); Push(&s,c); } } scanf("%c",&c); } if(!StackLen(s)) printf("The brackets are matched\n"); else printf("The brackets are not matched\n"); }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
下一篇:经典算法5:用分治法实现元素选择
最新资讯
热门推荐