C++ 模拟栈 stacks (数据结构实验)

来源:互联网 发布:时时彩缩水软件 编辑:程序博客网 时间:2024/06/13 02:52

非常不喜欢链表操作,  又因为 c++  STL 库里 自带 stack 函数,  但是  实验课 需要自己写,  好吧

模仿STL stack  写到一个结构体中,  这让我习惯了stack 函数的人很舒服。


1)输入一个十进制数,利用栈操作,将该数转换成n进制数。

2)输入一个表达式,表达式中包括三种括号“()”、“[]”和“{}”,判断该表达式的括号是否匹配。


so easy、



#include <iostream>#include <string.h>#include <queue>#include <stdlib.h>#include <stack>#include <stdio.h>using namespace std;/*1)输入一个十进制数,利用栈操作,将该数转换成n进制数。(2)输入一个表达式,表达式中包括三种括号“()”、“[]”和“{}”,判断该表达式的括号是否匹配。*/const int n =12;const int nn=12;typedef struct Stack{    char *x;    int top;    int size;    void InitStack()    {        x= (char *)malloc(n*sizeof(char));        top=0;        size=n;    }    bool emptys()    {        if(top==0)            return true;        return false;    }    void Push_back(char num)    {        if(top>=size)        {            x= (char *) realloc(x,size+nn*sizeof(char));            if(!x) return;            size+=nn;        }        x[top++]=num;    }    void Pop(char &num)    {        if(top==0)return;        num=x[--top];    }    char Gettop()    {        if(top==0) return -1;        return x[top-1];// top  下一个    }}stacks;int main(){  stacks S;  S.InitStack();  int num,z;  char y=0;  cin>>num>>z;  while(num)  {      char xy;      xy =(char) (num%z +'0');      S.Push_back(xy);    num/=z;  }  while(!S.emptys())  {      if(S.Gettop()<='9'&&S.Gettop()>='0')        printf("%c",S.Gettop());      else        printf("%c",S.Gettop()-'0'+'A'-10);      S.Pop(y);  }  cout<<endl;  stacks ST;  ST.InitStack();  string str;  cin>>str;  int len=str.length();  for(int i=0;i<=len;i++)  {      if(str[i]=='('||str[i]=='['||str[i]=='{')            ST.Push_back(str[i]);      else if(str[i]==')'||str[i]==']'||str[i]=='}')            ST.Pop(y);  }    printf(ST.emptys()?"YES\n":"NO\n");    return 0;}