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>usingnamespace std;// To Accommodate More Than One Data Typetemplate<class T>classStack{// Create (Node) As A structstructNode{
T Val;// Create Pointer (Next) Points On NodeNode*Next;};Node*Top,* X;public:// Empety Constaractor To Initialize (Top) As NULLStack(){Top= NULL;}// Create Add Function To Add New ElementvoidAdd(T val){//*Ptr As Pointer Because It Is Linked StackNode*Ptr=newNode;// Use (new) Nodeif(Ptr== NULL)
cout <<"Stack Add Cannot Allocate Memory";else{// Assigning The Value To The PointerPtr->Val= val;// Use (->) Because We Are Dealing With PointerPtr->Next=Top;Top=Ptr;}}// To Check Stack Is Empety Or NoboolCheckIsEmpety(){// Case Top == NULL That's Mean The Stack Is EmpetyreturnTop== NULL;}// To Erase The ElemetsvoidErase(){if(CheckIsEmpety()){
cout <<"Stack Is Empety";}else{// Create Temporary Pointer Points To *TopNode*Temp=Top;// To Move Top A Step DownTop=Top->Next;// Make The Temporary Pointer NULLTemp=Temp->Next= NULL;// Then Delete TempdeleteTemp;}}// To Save Temp Value's Before Delete ItvoidSave(T&SaveValue){if(CheckIsEmpety()){
cout <<"Stack Is Empety";}else{// To Save Top Value Before Delete ItSaveValue=Top->Val;
cout <<"Save Value : "<<SaveValue;}}// To Get Top ElementvoidGetTop(T&Value){if(CheckIsEmpety())
cout <<"Stack Is Empety";elseValue=Top->Val;
cout <<"\nThe Top Element : "<<Value<<"\n";}// Print FunctionvoidPrint(){
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 Topint 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();}
السؤال
Shahd Moustafa
My teacher tells me: you are still calling delete on a null pointer instead of deallocating the nodes.
1 جواب على هذا السؤال
Recommended Posts
انضم إلى النقاش
يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.