1000.Stack Implementation
时间限制:1秒 内存限制:256兆
题目描述
Implement the following Stack:
typedef int Stack_entry;
class Stack {
public:
// Standard Stack methods
Stack();
bool empty() const;
/* Returns true if the stack is empty, otherwise, returns false.
/
int size() const;
/ Returns the number of elements in the stack.
*/
void push(const Stack_entry &item);
/*item is pushed into the stack and it becomes the new top element.
*/
void pop();
/*The top item is removed if the stack is not empty.
Otherwise, nothing happens.
*/
const Stack_entry & top() const;
/* The top element is returned by item if the stack is not empty,
and the stack remains unchanged.
Nothing happens if the stack is empty.
*/
// Safety features
~Stack();
Stack(const Stack &original);
void operator =(const Stack &original);
};
typedef Stack MyStack;
//or if your are using templates
typedef Stack MyStack;
提示
Submit your implementations only.
本题有意思的点:
1.自定义拷贝构造函数是一种良好的编程风格,它可以阻止编译器形成默认的拷贝构造函数,防止出错。
2.一般来说,如果类需要复制构造函数,也就需要赋值操作符。
我的代码>>>
// EE_While Sicily
// E-mail:1026224216@qq.com
// SUN YAT-SEN UNIVERSITY 17 SDCS
// A master also used to be a novice.
typedef int Stack_entry;
class Stack {
public:
Stack_entry str[100];// 定义栈的容量
int pos;//目前表达式位置 或 栈内元素数量
Stack() {
pos = 0;//空栈
}
bool empty() const {
return pos == 0;//如果栈空,返回true,否则返回false
}
int size() const {
return pos;//返回栈内元素数量
}
void push(const Stack_entry &item) {
str[pos++] = item;//元素入栈
}
void pop() {
if (pos == 0) return;//若栈为空,无操作
pos--;//元素出栈
}
Stack_entry top() const {
if (pos == 0) return -1;//若栈为空,无操作
return str[pos - 1];// 获取栈顶元素
}
~Stack() {}//析构函数
Stack(const Stack & original) {//拷贝构造函数
for (int i = 0; i < original.pos; i++) {
str[i] = original.str[i];
}
pos = original.pos;
}
void operator = (const Stack & original) {//赋值运算符重载
*this = original;
}
};
typedef Stack MyStack;
from:EE_While
Email:1026224216@qq.com