数据结构--栈的基本操作及应用(数制转换)

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>
#define TRUE 1
#define FALSE 0

#define ERROR 0
#define INFEASIBLE -1

typedef int Status;
typedef int Boolean;
typedef int SElemType;

#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 2

struct SqStack 
{
     SElemType *base;
     SElemType *top;
     SElemType stacksize;
};

void InitStack(SqStack &S){
    if(!(S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType))))
        exit(OVERFLOW); // 存储分配失败
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;

}

void DestroyStack(SqStack &S){
      free(S.base);
      S.base =NULL;
      S.top=NULL;
      S. stacksize=0;
}

void ClearStack(SqStack &S){
    S.top=S.base;
}

Status StackEmpty(SqStack S){
          if (S.top ==S.base)
              return TRUE;
          else
              return FALSE;
}


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

Status GetTop(SqStack S,SElemType &e){
     if (S.top>S.base)
     {
         e=*(S.top-1);
         return OK;
     }
     else
         return ERROR;

}

void Push(SqStack &S,SElemType e){
      
      if (S.top-S.base>=S.stacksize)
      {
           S.base=(SElemType *)realloc(S.base,(S.stacksize+STACK_INCREMENT)*sizeof(SElemType));
           if (!S.base) exit(OVERFLOW);
           S.top=S.base+S.stacksize;
           S.stacksize+=STACK_INCREMENT;
           
           
      }
      *(S.top)++=e;

}

Status Pop(SqStack &S ,SElemType &e){
      if(S.top==S.base)
           return ERROR;
      e=*--S.top;
      return OK;

}

void StackTraverse(SqStack S,void(*visit)(SElemType))
{ // 从栈底到栈顶依次对栈中每个元素调用函数visit()
    while(S.top>S.base)
        visit(*S.base++);
    printf("\n");
}

void print(SElemType c)
{
    printf("%d ",c);
}

void main()
{
    int j;
    SqStack s;
    SElemType e;
    InitStack(s);
    for(j=1;j<=12;j++)
        Push(s,j);
    printf("栈中元素依次为:");
    StackTraverse(s,print);
    Pop(s,e);
    printf("弹出的栈顶元素 e=%d\n",e);
    printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
    GetTop(s,e);
    printf("栈顶元素 e=%d 栈的长度为%d\n",e,StackLength(s));
    ClearStack(s);
    printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
    DestroyStack(s);
    printf("销毁栈后,s.top=%u s.base=%u s.stacksize=%d\n",s.top,s.base, s.stacksize);

    //数值转换
    printf("\n\n**********************数制转换*****************************\n\n");
    SqStack Num;
    InitStack(Num);
    int N;
    printf("请输入N:\n");
    scanf("%d",&N);
    while (N)
    {
        Push(Num,N%8);
        N=N/8;
    }
    while(!StackEmpty(Num)){
         Pop(Num,e);
         printf("%d",e);
    }
}
printf("\n");

posted @ 2014-08-30 00:48  CSER_think more  阅读(594)  评论(0编辑  收藏  举报