数据结构之栈

简单的实现以下栈的数据结构:

      

#include <iostream>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack{
    int *Base;
    int Top;
    int Size;
}Sqstack;
const int Const_size = 20;
using namespace std;
// 初始化操作
int Init(Sqstack &S, int Size)
{
    S.Base = (int*)malloc(Size *sizeof(int));
    if(!S.Base)
          return 0;
    S.Size = Size;
    S.Top = 0;
    return 1;
}
//判空操作
int Is_empty(Sqstack &S)
{
          if(!S.Top)
                    return 1;
          return 0;
}
//清空操作
void Is_clear(Sqstack &S)
{

          S.Top = 0;
}
// 求栈长度
int Is_length(Sqstack &S)
{
          return S.Top;
}
// 入栈操作
int Push(Sqstack &S, int e)
{

          int *Newbase;
          if(S.Top == S.Size){
                    Newbase = (int *)realloc(S.Base, (S.Size+Const_size)*sizeof(int));
                    if(!Newbase)
                              return 0;
                    S.Base = Newbase;
                    S.Size += Const_size;
          }
          S.Base[S.Top++] = e;
          return 1;
}
// 出栈操作
int Pop(Sqstack &S, int &e)
{
          if(!S.Top)
                    return 0;
          e = S.Base[--S.Top];
          return 1;
}
// 栈顶元素
int Is_getNumber(Sqstack S, int &e)
{
          if(!S.Top)
                    return 0;
          e = S.Base[S.Top-1];
          return 1;
}
int main()
{
    Sqstack qt;
    int num;
    int e;
    cout << "输入栈规模:" << endl;
    cin >> num;
     Init(qt, num);
     cout << "入栈:" << endl;
     int tmp;
     for(int i=0; i<num; i++){
          cin >> tmp;
          if(!Push(qt, tmp)){
          cout << "出错!" << endl;
          break;
          }
     }
      if(Is_empty(qt))
          cout << "栈为空" << endl;
          else
          cout << "栈非空" << endl;
     if(!Is_getNumber(qt, e))
          cout << "出错!" << endl;
     else
          cout << "栈顶元素为:" <<  e << endl;
          if(!Is_length(qt))
                    cout << "栈长度为:"<<  0 << endl;
          else
                    cout << "栈长度为:" << Is_length(qt) << endl;
         // Is_clear(qt);

     for(int i=0; i<num; i++)
     {
              if(!Pop(qt, e))
              {
                 cout << "出错!" << endl;
                 break;
              }
              else
              {
                  cout << e << endl;
              }
     }
      if(Is_empty(qt))
          cout << "栈为空" << endl;
          else
          cout << "栈非空" << endl;
          if(!Is_length(qt))
                    cout << "栈长度为:" <<  0 << endl;
          else
                    cout << "栈长度为:" << Is_length(qt) << endl;



    return 0;
}

 

posted @ 2014-10-15 17:36  tt_tt--->  阅读(83)  评论(0编辑  收藏  举报