Operation of data structure c++ sequential stack

Implementation of sequential stack

const int StackSize = 10; //10是示例性的数据,根据实际问题具体定义
template //定义模板类SeqStack
class SeqStack
{
    
    
public:
    SeqStack( ); //构造函数,初始化一个空栈
    ~SeqStack( ); //析构函数
    void Push( DataType x ); //入栈操作,将元素x入栈
    DataType Pop( ); //出栈操作,将栈顶元素弹出
    DataType GetTop( ); //取栈顶元素(并不删除)
    int Empty( ); //判断栈是否为空
private:
    DataType data[StackSize]; //存放栈元素的数组
    int top; //游标,栈顶指针,为栈顶元素在数组中的下标
};

The push operation code of the sequential stack
is as follows:

template<typename DataType>
void SeqStack<DataType>::Push(DataType x)
{
    
    
    if(top==StackSize-1)
    throw"上溢";
    data[++top]=x;
}

The pop-up operation code of the sequential stack
is as follows:

template<typename DataType>
DataType SeqStack<DataType>::Pop()
{
    
    
    DataType x;
    if(top==-1)
    throw"下溢";
    x=data[top--];
    return x;
}

Application of sequence stack
Input binary number and output decimal number.
insert image description here
code show as below:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10

typedef char ElemType;
typedef struct
{
    
    
   ElemType *base;
   ElemType *top;
   int stackSize;
}sqStack;

void InitStack(sqStack *s)
{
    
    
     s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
     if(!s->base)
     {
    
    
        exit(0);
     } 
     
     s->top = s->base;
     s->stackSize = STACK_INIT_SIZE;
}

void Push(sqStack *s,ElemType e)
{
    
    
   if(s->top - s->base >= s->stackSize)
   {
    
    
       s->base = (ElemType *)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
       if(!s->base)
       {
    
    
           exit(0);
       }       
   }
   *(s->top) = e;
   s->top++;  
}

void Pop(sqStack *s,ElemType *e)
{
    
    
    if(s->top == s->base)
    {
    
    
        return;
    }
    *e=*--(s->top);
}

int StackLen(sqStack s)
{
    
    
   return(s.top - s.base); 
}

int main()
{
    
    
   ElemType c;
   sqStack s;
   int len,i,sum=0;
   printf("请输入二进制数,输入#结束!\n");
   scanf("%c",&c);
   while(c!='#')
   {
    
    
       Push(&s,c);
       scanf("%c",&c);
   }
    
    getchar();
    
    len=StackLen(s);
    printf("栈得当前容量是:%d\n",len);

    for (i=0;i<len;i++)
    {
    
    
       Pop(&s,&c);
       sum=sum+(c-48)*pow(2,i);    
    }
    printf("转化的十进制数为:%d\n",sum);
return 0; 
}

Guess you like

Origin blog.csdn.net/qq_51344334/article/details/119803525