My teacher tells me: you are still calling delete on a null pointer instead of deallocating the nodes.
// Stack Using Linked List Implementation.cpp "Using Pointer"
// Val1->Val2->...Val15->Null
// Val + Pointer = Node
#include <iostream>
using namespace std;
// To Accommodate More Than One Data Type
template <class T>
class Stack
{
// Create (Node) As A struct
struct Node {
T Val;
// Create Pointer (Next) Points On Node
Node* Next;
};
Node* Top, * X;
public:
// Empety Constaractor To Initialize (Top) As NULL
Stack() {
Top = NULL;
}
// Create Add Function To Add New Element
void Add(T val) {
//*Ptr As Pointer Because It Is Linked Stack
Node* Ptr = new Node;// Use (new) Node
if (Ptr == NULL)
cout << "Stack Add Cannot Allocate Memory";
else{
// Assigning The Value To The Pointer
Ptr->Val = val;// Use (->) Because We Are Dealing With Pointer
Ptr->Next = Top;
Top = Ptr;
}
}
// To Check Stack Is Empety Or No
bool CheckIsEmpety() {
// Case Top == NULL That's Mean The Stack Is Empety
return Top == NULL;
}
// To Erase The Elemets
void Erase() {
if (CheckIsEmpety()) {
cout << "Stack Is Empety";
}
else {
// Create Temporary Pointer Points To *Top
Node* Temp = Top;
// To Move Top A Step Down
Top = Top->Next;
// Make The Temporary Pointer NULL
Temp = Temp->Next = NULL;
// Then Delete Temp
delete Temp;
}
}
// To Save Temp Value's Before Delete It
void Save(T&SaveValue) {
if (CheckIsEmpety()) {
cout << "Stack Is Empety";
}
else {
// To Save Top Value Before Delete It
SaveValue = Top->Val;
cout << "Save Value : " << SaveValue;
}
}
// To Get Top Element
void GetTop(T&Value) {
if (CheckIsEmpety())
cout << "Stack Is Empety";
else
Value = Top->Val;
cout << "\nThe Top Element : " << Value << "\n";
}
// Print Function
void Print() {
X = Top;
cout << "\nElements In The Stack : [";
while (X != NULL)
{
cout << X->Val << " ";
X = X->Next;
}
cout << "]\n";
}
};
int main()
{
Stack<int> obj;
// Add Some Values
obj.Add(15);
obj.Add(70);
obj.Add(23);
// Print The Values
obj.Print();
//Get The Top
int k = 0;
obj.GetTop(k);
obj.Save(k);
// After Remove Top Element
obj.Erase();
// Print After Remove Top Element
cout << "\nAfter Remove Top Element";
obj.Print();
}