Chinaunix首页 | 论坛 | 博客
  • 博客访问: 231732
  • 博文数量: 68
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 612
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-04 22:38
文章分类

全部博文(68)

文章存档

2010年(2)

2009年(12)

2008年(54)

我的朋友

分类: C/C++

2008-09-19 20:50:46

#define Stack_Init_Size 100
#define StackIncreament 10
#include
#include
typedef struct{
 int *top;
 int *base;
 int stacksize;
}SqStack;//定义栈


void Push(SqStack &s, int e)
{
 if(s.top -s.base >=s.stacksize) {//本满,追加存储空间
  s.base=(int *)realloc(s.base,
        (s.stacksize+StackIncreament)*sizeof(int));
  if(!s.base) printf("error\n");
  s.top=s.base+s.stacksize;
  s.stacksize+=StackIncreament;
 }
 *s.top++=e;
}//向栈顶插入元素e


void InitStack(SqStack &s)
{
 s.base=(int *)malloc(Stack_Init_Size*sizeof(int)); //栈底地址
 if(!s.base) printf("error\n");
 s.top=s.base;
 s.stacksize =Stack_Init_Size;//构造空栈
 printf("输入6个栈元素:");
 for(int i=0;i<6;i++)
 {
  int a;
  scanf("%d",&a);
  Push(s,a);//向栈中插元素
 }
}//初始化栈

int StackEmpty(SqStack s)
{
 if(s.top ==s.base ) return 1;
 else return 0;
}//判断栈是否为空

 

void Pop(SqStack &s, int &e)
{
 if(s.top ==s.base ) printf("error2\n");
 e=*--s.top ;
}//删除栈顶元素

void Print(SqStack s)
{
 while(!StackEmpty(s))
 {
  int e;
  Pop(s,e);
  printf("%d ",e);
 }
}//输出栈元素

void GetTop(SqStack s,int &e)
{
 if(s.base ==s.top ) printf("error3\n");
 e=*(s.top -1);
}//取栈顶元素

int StackLength(SqStack s)
{
 return (s.top-s.base);
}

 

main()
{
 int a;//存储栈顶元素
 int b;//存储栈的长度
    SqStack s;
    InitStack(s);
    Print( s);
    GetTop(s,a);
    b=StackLength(s);
 printf("所取栈顶元素:%d\b",a);
 printf("栈的长度:%d",b);
 return 0;
}

阅读(758) | 评论(0) | 转发(0) |
0

上一篇:同步与异步

下一篇:栈的链式存储

给主人留下些什么吧!~~