C++ to implement a chain stack instance code

  • 2020-04-02 00:57:43
  • OfStack

Custom a chain stack, c++ language implementation, shortcomings, also hope to correct!

//Mystack.cpp: defines the entry point for the console application.
//Construct a chain stack by yourself, with functions such as push, pop, top, size, and empty
#include "stdafx.h"
#include <iostream>
using namespace std;
//Construct the nodes of the stack
template <class T>
struct NODE
{
 NODE<T>* next;
 T data;
};
template <class T>
class MyStack
{
public:
 MyStack()
 {
  phead = new NODE<T>;
  if (phead == NULL)
  {
   cout << "Failed to malloc a new node. " << endl;
  }
  else
  {
   phead->data = NULL;
   phead->next = NULL;
  }
 }

 //Into the stack
 void push(T e)
 {
  NODE<T>* p = new NODE<T>;
  if (p == NULL)
  {
   cout << "Failed to malloc a new node. " << endl;
  }
  else
  {
   p->data = e;
   p->next = phead->next;
   phead->next = p;
  }
 }

 //Out of the stack
 T pop()
 {
  T e;
  NODE<T>* p = phead->next;
  if(p != NULL)
  {
   phead->next = p->next;
   e = p->data;
   delete p;
   return e;
  }
  else
  {
   cout << "There is no elements in the stack." << endl;
   return NULL;
  }
 }

 //Gets the top element of the stack
 T top()
 {
  T e;
  NODE<T>* p = phead->next;
  if (p != NULL)
  {
   e = p->data;
   return e;
  }
  else
  {
   cout << "There is no elements in the stack." << endl;
   return NULL;
  }
 }
 //Gets the number of elements in the stack
 int size()
 {
  int count(0);
  NODE<T>* p = phead->next;
  while (p != NULL)
  {
   p = p->next;
   count++;
  }
  return count;
 }
 //Determine if the stack is empty
 bool empty()
 {
  NODE<T>* p = phead;
  if (p->next == NULL)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
private:
 NODE<T>* phead;
};
int _tmain(int argc, _TCHAR* argv[])
{
 MyStack<int> sta;
 sta.push(1);
 sta.push(2);
 sta.push(3);
 cout << "The size of the stack now is " << sta.size() << endl;
 sta.pop();
 cout << "The top element is " << sta.top() << endl;
 cout << "The size of the stack now is" << sta.size() << endl;
 if (sta.empty())
 {
  cout << "This stack is empty." << endl;
 }
 else
 {
  cout << "This stack is not empty." << endl;
 }
 return 0;
}


Related articles: