Stack class C ++ implementation

Source: Internet
Author: User

Stack classes written by myself may have few functions or many errors, but at least I tested them correctly ,;

Code:

#include <iostream>using namespace std;template <class T>class node{public:node<T>* next;T val;node():next(NULL),val(){};node(T v):next(NULL),val(v){};};template <class T>class my_stack{public:my_stack();~my_stack();void init_stack();bool is_empty();size_t get_len();    T* get_top();void push(const T& e);    void pop(T& e);void display();private:    node<T>* top;    size_t len;};template <class T>my_stack<T>::my_stack(){   top  = NULL;   len = 0;}template <class T>my_stack<T>::~my_stack(){node<T>* pre = top;if (top){       delete top;   top = pre->next;   pre = pre->next;}len = 0;}template <class T>bool my_stack<T>::is_empty(){return len == 0;}template <class T>size_t my_stack<T>::get_len(){return len;}template <class T>void my_stack<T>::push(const T& e){   node<T>* tmp = new node<T>(e);   if (top == NULL)   {   top =tmp;   }   else   {   tmp->next = top;   top = tmp;   }   ++len;}template <class T>void my_stack<T>::pop(T& e){if(is_empty())throw new exception("The stack is empty!");e = top->val;    if (len ==1)    {top  = NULL;    }else{        node<T>* tmp = top;        top = top->next;delete tmp;}--len;   }template <class T>void my_stack<T>::display(){   node<T>* pre = top;   cout << "The stack is: ";   while(pre)   {   cout << pre->val << " ";   pre = pre->next;   }   cout << endl;}int main(){    my_stack<int> s;s.push(1);s.push(2);s.display();int e = 0;s.pop(e);s.display();cout << e;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.