#include
#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;
}
重载“-”为出栈?“<<”?
判栈有判空和判满。
#include
using namespace std;
template
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++]<
}
bool operator ()() const
{
return top == size;
}
bool Isfull() const
{
return top == 0;
}
};
template
Stack
{
this->size = size;
top = size;
space = new T [size];
}
template
void Stack
{
if(!Isfull())
space[--top] = t;
}
int main()
{
Stack
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
cout<}
这个没问题,如果是重载 - 改为:
#include
using namespace std;
template
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++]<
}
bool operator ()() const
{
return top == size;
}
bool Isfull() const
{
return top == 0;
}
};
template
Stack
{
this->size = size;
top = size;
space = new T [size];
}
template
void Stack
{
if(!Isfull())
space[--top] = t;
}
int main()
{
Stack
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
-s;
}
但是这个在VC下不行,在codeblocks下使用mingw32-g++.exe可以正常编译执行,运行截图:
请参考