1002. The stack class

来源:互联网 发布:mac hosts文件位置 编辑:程序博客网 时间:2024/06/07 22:10


1002. The stack class
 
    
Time Limit: 1sec    Memory Limit:256MB
Description
 
You are to implement the following Stack class template, using the nontype parameter capacity to allocate the capacity of the stack, i.e. maximum elements that can be stored in the stack.
 
template<typename T, int capacity>
class Stack
{
public:
    Stack();                 // Constructs an empty stack.
    bool empty();         // Returns true if the stack is empty.
    T peek();               // Returns the element at the top of the stack without removing it from the stack.
    void push(T value); // Stores an element into the top of the stack.
    T pop();                 // Removes the element at the top of the stack and returns it.
    int size();               // Returns the number of elements in the stack.
private:
    T* elements;          // Points to an array that stores elements in the stack.
    int num;                 // The number of the elements in the stack.
};
 
Your submitted source code should only include the implementation of Stack class template, without the declaration above.
No main() function should be included.

 


// Problem#: 14402// Submission#: 3726490// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/// All Copyright reserved by Informatic Lab of Sun Yat-sen University#include<iostream>using namespace std;template<typename T, int capacity>Stack<T,capacity> :: Stack(){      elements=new T[capacity];      num=0;      } template<typename T, int capacity>bool Stack<T,capacity> :: empty(){     return num==0;     }template<typename T, int capacity>T Stack<T,capacity> :: peek(){        return elements[num-1];        }template<typename T, int capacity>void Stack<T,capacity> :: push(T value){      elements[num++]=value;}template<typename T, int capacity>T Stack<T,capacity> :: pop(){        return elements[--num];               }template<typename T, int capacity>int Stack<T,capacity> :: size(){    return num;}                                 


0 0