建立一个整数堆栈类Stack,栈的默认大小为10元素,能够完成数据的入栈和出栈处理

如题所述

#include <stdio.h>
#define MaxSize 100

typedef int ElemType;//定义数据类型

//定义顺序栈
typedef struct
{
ElemType data[MaxSize];//数据域
int top;//如果定义top=-1,编译出错
}SeqStack;

//栈初始化
int InitStack(SeqStack &s)
{
s.top=-1;//初始化栈顶,指向空
return 1;
}

//入栈
int Push(SeqStack &s,ElemType x)
{
if (s.top == MaxSize -1 )
{
printf("栈已满,不能入栈.\n");
return 0;
}
else
{
s.top++;//栈顶指针上移
s.data[s.top] = x;//数据元素入栈
}
return 1;
}

//出栈
int Pop(SeqStack &s,ElemType &x)
{
if (s.top == -1)
{
printf("栈为空,不能出栈.\n");
return 0;
}
else
{
x=s.data[s.top];//取出栈顶元素值
s.top--;//栈顶指针下移
}
return 1;
}

int main(void)
{
int i,x;

SeqStack st;

//栈初始化
InitStack(st);
//入栈
printf("入栈...\n");
for(i=0;i<8;i++)
if(Push(st,i+11)!=1)
return 1;

//出栈
printf("出栈...\n");
if(Pop(st,x)!=1)
return 1;
printf("弹出值:%d\n",x);

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-06-15

重载“-”为出栈?“<<”?
判栈有判空和判满。
#include<iostream>
using namespace std;
template <class T>

class Stack
{
private:
int size;
int top;
T *space;
public:
Stack(int n);
~Stack()
{
delete [] space;
}

void push( T t);

friend ostream& operator<<(ostream& out,Stack &st)
{
while(!(st.operator()()))
out<< st.space[st.top++]<<endl;
return out;
}

bool operator ()() const
{
return top == size;
}

bool Isfull() const
{
return top == 0;
}
};

template <class T>
Stack<T>::Stack(int size)
{
this->size = size;
top = size;
space = new T [size];
}

template <class T>
void Stack<T>::push(T t)
{
if(!Isfull())
space[--top] = t;
}

int main()
{
Stack<int>s(20);//可以指定栈的大小
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);

cout<<s;
}
这个没问题,如果是重载 - 改为:
#include<iostream>
using namespace std;
template <class T>

class Stack
{
private:
int size;
int top;
T *space;
public:
Stack(int n);
~Stack()
{
delete [] space;
}

void push( T t);

friend Stack & operator -(Stack &st)
{
while(!(st.operator()()))
cout<< st.space[st.top++]<<endl;

}

bool operator ()() const
{
return top == size;
}

bool Isfull() const
{
return top == 0;
}
};

template <class T>
Stack<T>::Stack(int size)
{
this->size = size;
top = size;
space = new T [size];
}

template <class T>
void Stack<T>::push(T t)
{
if(!Isfull())
space[--top] = t;
}

int main()
{
Stack<int>s(20);//可以指定栈的大小
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);

-s;
}
但是这个在VC下不行,在codeblocks下使用mingw32-g++.exe可以正常编译执行,运行截图:
请参考