具体操作如下:
/*
* stack.c
*
* Created on: 2010-12-20
* Author: qiang
*/
#include <stdio.h>
#include <stdlib.h>
//宏定义
#define STACK_INIT_SIZE 10 /*存储空间初始分配量*/
#define STACK_INCREMENT 2 /*存储空间分配增量*/
//定义顺序栈的结构体
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *base; //栈顶
SElemType *top; //栈底
int stacksize; //当前已分配的存储空间,以元素为单位;注意长度(当前情况)与大小(最大限度)的区别
}SqStack;
//初始化顺序栈
Status InitStack(SqStack* S)
{
S->base = (SElemType*)malloc((STACK_INIT_SIZE)*sizeof(SElemType));
if(S->base==NULL)
exit(-1);
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return 0;
}
//销毁顺序栈
Status DestroyStack(SqStack* S)
{
free(S->base); //释放内存-与malloc成对
S->base = NULL; //释放指针变量
S->top = NULL;
S->stacksize = 0;
return 0;
}
//清空顺序栈
Status ClearStack(SqStack *S)
{
S->top = S->base;
return 0;
}
//判断顺序栈是否为空
Status StackEmpty(SqStack* S)
{
if(S->top == S->base)
return 0;
else
return -1;
}
//顺序栈的长度-S所含元素个数
int StackLength(SqStack* S)
{
return S->top-S->base;
}
//取栈顶元素
Status GetTop(SqStack* S,SElemType* x)
{
if((S->top)<=(S->base))
return -1;
*x = *(S->top-1);
return 0;
}
//入栈元素e
Status Push(SqStack* S,SElemType e)
//void Push(SqStack* S,SElemType e)
{
//判断栈是否已满,已满则分配新的空间
if(StackLength(S)>=S->stacksize)
{
S->base = (SElemType*)realloc(S->base,(STACK_INCREMENT)*sizeof(SElemType)); //重新分配内存
if(S->base==NULL)
return -1;
S->top = S->base + S->stacksize; //由于内存重新分配,则top也相应的改变了,而此时的stacksize正好和length相等
S->stacksize += STACK_INCREMENT;
}
*(S->top++) = e; //将元素e入栈,然后top增1
return 0;
}
//栈顶元素x出栈
Status Pop(SqStack* S,SElemType* x) //函数需要返回x的值,所以这里我们采用指针形式返回其值
{
if(StackLength(S)<=0)
{
printf("Pop error! \n");
return -1;
}
*x = *(--S->top); //说明栈顶指向最后一个元素的下一位置
return 0;
}
int main()
{
SqStack S;
//初始化顺序栈
if(InitStack(&S)!=0) //这里不能采用指针的形式去调用函数,否则出现段错误-指针使用错误
{
printf("InitStack error! \n");
return -1;
}
printf("InitStack ok! \n");
//得出顺序栈的长度
int len = StackLength(&S);
printf("Length of stack is %d! \n",len);
//元素x入栈
int i;
printf("请输入要入栈的数:\n");
while(scanf("%d",&i)!=EOF)
{
Push(&S,i); //仅仅传递参数,而不返回参数,则无需用指针,地址
printf("Push data:%d! \n",i);
}
//获得栈顶元素的值
int p;
if(GetTop(&S,&p)==0)
//GetTop(&S,&p);
printf("The top value is %d! \n",p);
//栈顶元素x出栈
int m;
while(Pop(&S,&m)==0)
printf("Pop data:%d! \n",m);
//销毁堆栈
if(DestroyStack(&S)!=0)
{
printf("DestroyStack error! \n");
return -1;
}
printf("Destroy ok! \n");
return 0;
}
|
运行结果:
qiang@LinuxSir:~/workspace/Stack/Debug$ ./Stack
InitStack ok!
Length of stack is 0!
请输入要入栈的数:
1
Push data:1!
2
Push data:2!
3
Push data:3!
The top value is 3!
Pop data:3!
Pop data:2!
Pop data:1!
Pop error!
Destroy ok!
|
文件: | Stack.zip |
大小: | 26KB |
下载: | 下载 |
|
阅读(1087) | 评论(0) | 转发(0) |