数据结构学到了栈的部分了,呵呵自己写了下程序,希望来访的朋友多多提出意见啊!大家共同进步
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 10
#define OK 0;
#define ERROR -1;
struct Stack{
char *base;
char *top;
int count;
int stacksize; //stack表示的是当前已经分配的存储空间,以元素为单位
};
struct Stack head;
//取栈顶元素
char* GetTop()
{
struct Stack *S;
char *e=(char*)malloc(sizeof(char));
S=&head;
if(S->base==S->top)
{
printf("栈空/n");
exit(0);
}
*e=*(S->top-1); //top指向的是栈顶的下一个位置
return e;
}
//插入元素e为新的栈顶元素
int Push(char *e)
{
struct Stack *S;
S=&head;
if((S->top-S->base)==S->stacksize) //如果栈满的话则追加空间
{
head.base=(char *)realloc(head.base,(head.stacksize+STACKINCREMENT)*sizeof(char));
if(!head.base)
exit(0);
head.top=head.base+head.stacksize;
head.stacksize=head.stacksize+STACKINCREMENT;
}
*S->top++=*e;
return OK;
}
//当栈顶不为空时,删除栈顶元素
char Pop()
{
struct Stack *S;
S=&head;
if(S->top==S->base)
exit(0);
return (*--S->top);
}
void print()
{
struct Stack *S;
S=&head;
char *p;
p=(char *)malloc(sizeof(char));
if(S->base==S->top)
{
printf("空栈/n");
exit(0);
}
while(S->base!=S->top)
{
*p=Pop();
printf("p->%c/n",*p);
p=(char *)malloc(sizeof(char));
p++;
}
}
int main()
{
char buf[30],*z;
int i,count;
head.base=(char *)malloc(STACK_INIT_SIZE * sizeof(char));
if(!head.base)
exit(0);
head.top=head.base;
head.stacksize=STACK_INIT_SIZE;
head.count=0;
//构造栈
for(i=0;i<15;i++)
{
scanf("%c",&buf[i]);
getchar();
Push(&buf[i]);
head.count++;
}
printf("构造栈成功:/n");
print();
//读栈顶元素
count=head.count;
while(count)
{
++head.top;
count--;
}
z=GetTop();
printf("取出的栈顶元素是:%c/n",*z);
print();
count=head.count;
while(count)
{
++head.top;
count--;
}
//删除栈顶元素
printf("成功删除栈顶元素:%c/n",Pop());
head.count--;
print();
free(head.base);
return 0;
}