定义结构如下: #define STACK_MAX 100 struct Stack { void *stack_array[STACK_MAX]; int top; }stack; 堆栈定义如下: // 版权所有 (C)2007, ***(成都)有限公司。 // // 描述: //6.1 实现堆栈 //大家都知道堆栈是一个先进后出的数据结构,请用数组这种物理上连续的数据结构实现一个堆栈。 //要求: //1、该堆栈可以存储void*指针,堆栈最大为100; //2、并提供相关堆栈操作push(void *) //void *pop() //3、用该堆栈来模拟一个函数的调用,参数入栈顺序按照从右向左的方式入栈,即给一个 //字符串"func(aa, bb)",入栈顺序为func、bb、aa,出栈顺序为aa、bb、func.请将其打印出来。 //4、这里为降低难度,没有使用参数类型,有兴趣的同学可以完成带参数类型的解析 // 作者:陈进宇 chenjinyu_china@yeah.net // 日期:start:2009/3/7 end:2009/3/10 #include <iostream> #include "Head.h" void push(void *source);//压栈函数申明 void *pop();//出栈函数申明 void my_split(char *psrc, char **ppdata,char ***pppsplit, int *ncount); void main() { stack.top = 0; char *pdata,**ppsplit,**pppop = new char*[10];//指针的指针可看成指针数组,数组里存放的是地址char *ppsplit[]; int ncount; //char *p1,*p2,*p3; char szSource[] = "func(aa,bb,vv,cc);"; my_split(szSource,&pdata,&ppsplit,&ncount); printf("push stack:/n"); for(int i = 0;i < ncount;i++) { printf("%s/n",ppsplit[i]); push(ppsplit[i]); } printf("pop stack :/n"); for(int j = 0; j < ncount;j++ ) { pppop[j] = (char *)pop(); printf("%s/n",pppop[j]); } for(int i = 0 ;i < 100;i++) { stack.stack_array[i] = NULL; } //用完要释放 delete[] pdata; delete[] ppsplit; delete[] pppop; } void push(void *source) { if(stack.top < 100) { stack.stack_array[stack.top] = source; stack.top++; } else { printf("Memory short"); } } void *pop() { if(stack.top >= 0) { stack.top --; return stack.stack_array[stack.top]; } else { printf("Memory empty!"); return 0; } } void my_split(char* psrc, char** ppdata,char*** pppsplit, int *ncount)//ppdata指向开辟一块空间的首地址 { char* pstart = psrc; char* pfind; char* pdest; int nlen = strlen(psrc); pdest = *ppdata = new char[nlen];//存放字符串的地址.pdest 是指针变量,指向开辟空间的首地址 *pppsplit = new char*[20];//存放指针 *ncount = 0; pfind = strchr(pstart,'('); (*pppsplit)[(*ncount)++] = pdest; strncpy(pdest,pstart,pfind - pstart); pdest += pfind - pstart; *pdest ++ = 0; for(pstart = pfind + 1;';'!= *(pfind+1);pstart = pfind + 1) { pfind = strchr(pstart,','); if(!pfind) pfind = strchr(pstart,')');//没有','就找')' (*pppsplit)[(*ncount)++] = pdest; strncpy(pdest,pstart,pfind - pstart); pdest += pfind - pstart; *pdest ++ = 0;//*pdest ++ = '/0'; } for(int i = (*ncount) >> 1;i >=1;i--) { char* t = (*pppsplit)[i]; (*pppsplit)[i] = (*pppsplit)[*ncount - i]; (*pppsplit)[*ncount - i] = t; } } //思想:在my_split函数中,开辟一个用于存放字符串的空间t,用pdest指向它。再用一个指针数组pppsplit用于存放pdest。当t存放了func/0时,把pdest给 //pppsplit,再移动pdest到/0后,再来一个aa/0,再把此时的地址(pdest)给pppsplit。