Delete node in linked list result in program collapse - c++

I was trying to delete a node in a linked list defined as follows:
typedef struct
{
char key[10];
char name[20];
int age;
}Data;
typedef struct Node
{
Data nodeData;
struct Node *nextNode;
}cltype;
And the the delete function is defined as below:
int clDeleteNode(cltype *head, char *key)
{
cltype *node, *htemp = new (cltype);
htemp = head;
node = head;
while (htemp)
{
if (strcmp(htemp->nodeData.key, key))
{
node->nextNode = htemp->nextNode;
delete htemp;
return 1;
}
else
{
node = htemp;
htemp = htemp->nextNode;
}
}
//delete mp
return 0;
}
And the problem is when I tried to invoke the the delete function in this form the program will collapse:
cout << "program demo for deleting node\n" << "input key:" << endl;
fflush(stdin);
cin >> key;
//scanf("%s", key);
//int i =
if (clDeleteNode(head, key))
{
cout << "Delete Successful" << endl;
}
else
{
cout << "Operation Failed" << endl;
}
clAllNode(head);
The screen will display "Delete Successful", but the clAllNode(...) function will not execute.And the clAllNode(...) functions works totally well at other place, so I guess there is something wrong with the delete operation,can someone tell me where I did wrong?
Thank you.

Related

C++ How do I fix Exception thrown: write access violation. this was nullptr. on Line 20

*Create a simple linked list program to create a class list containing
class node {
void *info;
node *next;
public:
node (void *v) {info = v; next = 0; }
void put_next (node *n) {next = n;}
node *get_next ( ) {return next;}
void *get_info ( ) {return info;}
};
Be able to initially fill the list. Provide functions to insert/append nodes and remove nodes from the linked list. Be able to display the contents of the list.
Write a little driver program with at least 5 values passed in (so that 5 nodes are created) as you insert/append, delete and display data, showing the programs operation.
Output: While displaying the data, make sure you use an informational label–using the terms “insert”, “append”, “remove” and any other term which displays the action. All data that is displayed must be displayed in a way in which the mentor can easily read and understand.*
My code runs but it throws Exception thrown: write access violation. this was nullptr. on Line 20 when I debug it. In the output it also stops at Delete 04 of my list and outputs no further data after line 156. I am not sure how to fix this. I tried to force it to output the new list with another cout statement but that did not work. Any assistance would be appreciated. Entire code below.
#include <iostream>
#include <iomanip>
using namespace std;
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) break;
previous = temp;
temp = temp->get_next();
}
previous->put_next(temp->get_next());
delete temp;
}
}
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
SOLUTION:
//Node.h
#pragma once
class Node
{
void* info;
Node* next;
public:
Node(void* v) { info = v; next = 0; }
void put_next(Node* n)
{
next = n;
}
Node* get_next()
{
return next;
}
void* get_info()
{
return info;
}
};
//List.h
#pragma once
#include "Node.h"
#include <iomanip>
class List {
Node* head;
public:
List() { head = NULL; };
void PRINT();
void APPEND(void* info);
void DELETE(void* info);
};
//List.cpp
#include <iostream>
#include "List.h"
using namespace std;
void List::PRINT() {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
cout << *(int*)temp->get_info();
cout << " => ";
cout << "Invalid" << endl;
}
else
{
while (temp != NULL)
{
cout << *(int*)temp->get_info();
cout << " --> ";
temp = temp->get_next();
}
cout << "Invalid" << endl;
}
}
void List::APPEND(void* info) {
Node* newNode = new Node(info);
newNode->put_next(NULL);
Node* temp = head;
if (temp != NULL)
{
while (temp->get_next() != NULL)
{
temp = temp->get_next();
}
temp->put_next(newNode);
}
else
{
head = newNode;
}
}
void List::DELETE(void* info) {
Node* temp = head;
if (temp == NULL)
{
cout << "Enter Values" << endl;
return;
}
if (temp->get_next() == NULL)
{
if ((int*)(temp->get_info()) == info)
{
delete temp;
head = NULL;
}
}
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info) {
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}
}
//Main.cpp
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List list;
int a = 04;
int b = 11;
int c = 12;
int d = 15;
int e = 29;
int* Node1 = &a;
int* Node2 = &b;
int* Node3 = &c;
int* Node4 = &d;
int* Node5 = &e;
cout << "Append: 04" << endl;
list.APPEND(Node1);
cout << "Append: 11" << endl;
list.APPEND(Node2);
cout << "Append: 12" << endl;
list.APPEND(Node3);
cout << "Append: 15" << endl;
list.APPEND(Node4);
cout << "Append: 29" << endl;
list.APPEND(Node5);
cout << endl << "Print List" << endl;
list.PRINT();
cout << endl << "Delete 04" << endl;
list.DELETE(Node1);
list.PRINT();
cout << "Start New List" << endl;
cout << endl << "Delete 12" << endl;
list.DELETE(Node3);
list.PRINT();
return 0;
}
So whenever you are deleting first node, you missed to set the head to the next node of head.
Commented at the parts which are modified in the else statement of DELETE function
Code:
else
{
Node* previous = NULL;
while (temp != NULL)
{
if ((int*)(temp->get_info()) == info){
// if node is head then changing the head
if (temp == head)
head = temp->get_next();
break;
}
previous = temp;
temp = temp->get_next();
}
// skip this operation if node is head
if (temp->get_next() != head)
previous->put_next(temp->get_next());
delete temp;
}

C++ Read Access Violation in Singly Linked List

I'm writing a program about creating a list of country, there seems to no error in my code but when debugging, I get the error: Unhandled exception thrown: Read access violation p was 0xFFFFFFFFFFFFFFFF, after I input some values.
Can anyone give me a hint or find me the mistake?
#include <cstring>
#include <string>
using namespace std;
this is my struct Provice.
struct Province
{
int Code;
string Name;
int Pop;
float Area;
};
struct node
{
struct Province data;
node* next;
};
struct List
{
node* head;
node* tail;
};
void Init(List &l)
{
l.head = NULL;
l.tail = NULL;
}
void add_tail(List& l, node* p)
{
if (l.head == NULL)
{
l.head = p;
l.tail = p;
}
else
{
l.tail->next = p;
l.tail = p;
}
}
I think I got some problem when I create a node here without initializing value, is this right ?
void inputListProvinces(List& l)
{
int n;
cin >> n;
int i = 0;
while(i<n)
{
node* p = new node;
cin >> p->data.Code;
cin.ignore();
getline(cin, p->data.Name);
cin.ignore();
cin >> p->data.Pop;
cin >> p->data.Area;
add_tail(l, p);
i++;
}
}
And the error happens here, but I dont know how to fix.
void outputListProvinces(List& l)
{
node* p = l.head;
while (p != NULL)
{
cout << p->data.Code << '\t'; /*Unhandled exception thrown: read access violation.
p was 0xFFFFFFFFFFFFFFFF*/
cout << p->data.Name << '\t';
cout << p->data.Pop << '\t';
cout << p->data.Area << '\t';
cout << endl;
p = p->next;
}
}
void outputProvince(node* p)
{
cout << p->data.Code << '\t';
cout << p->data.Name << '\t';
cout << p->data.Pop << '\t';
cout << p->data.Area << '\t';
}
void outputProvincesMore1MillionPop(List& l)
{
node* p = l.head;
while (p != NULL)
{
if (p->data.Pop > 1000)
{
outputProvince(p);
cout << endl;
}
p = p->next;
}
}
node* findProMaxArea(List& l)
{
node* n = l.head;
node* p = l.head;
while (p != NULL)
{
if (p->data.Area > n->data.Area)
{
n = p;
}
p = p->next;
}
return n;
}
int main()
{
List L;
Init(L);
inputListProvinces(L);
cout << "List of provinces:" << endl;
cout << "ID\t|Province\t|Population\t|Area" << endl;
outputListProvinces(L);
cout << "Provinces with a population of more than 1 million:" << endl;
outputProvincesMore1MillionPop(L);
cout << "The largest province:" << endl;
node* p = findProMaxArea(L);
if (p) outputProvince(p);
return 0;
}
Mistake is node never initializes its next pointer. You can only count on it being NULL if you set it to NULL, and the last node in the list MUST be NULLor the program can't find the end of the List and marches off into the wacky world of Undefined Behaviour.
Safest Fix: Add a constructor to node to make sure next is always initialized.
struct node
{
struct Province data;
node* next;
node(node* n = NULL): next(n)
{
}
};
There are other fixes, like making sure l.tail->next = NULL; at the end of inputListProvinces, but I don't think it's really worth the reduced overhead given the slow-ness of the console IO.
And if you do that, then you should also roll Init into List as a constructor:
struct List
{
node* head;
node* tail;
List(): head(NULL), tail(NULL)
{
}
};
This should leave you with the problem of a poorly-placed cin.ignore() consuming a character you don't want consumed.
Side note: Replace NULL with nullptr if available to your compiler and target C++ Standard revision. nullptr removes the bugs that can result from NULL being a glorified 0.

Undefined reference to another class?

I'm using a class within a class and I'm getting errors, I think it's a linking problem. I get "undefined reference to 'Node::setlink()', 'Node::getlink()', and etc. It's all the node functions I used in linked_list.cpp that are the problem.
For example, linked_list.cpp:(.text+0x9de): undefined reference to
`Node::getlink()'
Linked_list.cpp
#include "linked_list.hpp"
#include "node.hpp"
#include <iomanip>
#include <iostream>
using namespace std;
//default constructor
Linked_list::Linked_list(void)
{
head = new Node();
tail = new Node();
head->setlink(NULL);
tail->setlink(NULL);
cnt = 0;
}
//constructor
Linked_list::Linked_list(data x)
{
head = new Node();
tail = new Node();
Node *newnode = new Node(x);
head->setlink(newnode);
newnode->setlink(tail);
cnt++;
}
//class function
void Linked_list::insert_node(data x)
{
Node *newNode = new Node(x);
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
newNode->setlink(tail);
head->setlink(newNode);
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while(curr->getlink() != NULL || newNode->getupc() <= curr->getupc())
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
prev->setlink(newNode);
newNode->setlink(curr);
}
cnt++;
}
//Class function
void Linked_list::delete_node(int u)
{
char choice;
data temp;
Node *newNode = new Node();
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
delete newNode;
delete prev;
delete curr;
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while (curr->getlink() != NULL || curr->getupc() != u )
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
prev->setlink(curr->getlink());
cout << "Are you sure you want to delete?\n";
cin >> choice;
if (choice == 'y' || choice == 'Y')
{
delete curr;
cnt--;
}
else
{
choice = 'n';
}
}
}
//Class function
void Linked_list::traverse()
{
data temp;
Node *curr = new Node();
if (head == NULL)
{
delete curr;
cout << "The list is empty!\n";
}
else
{
curr->setlink(head->getlink());
while(curr->getlink() != NULL)
{
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
}
void Linked_list::retrieve_node(int u)
{
data temp;
Node *x;
x = new Node();
if (head == NULL)
{
delete x;
}
else if (head != NULL)
{
x->setlink(head->getlink());
while (x->getlink() != NULL || x->getupc() != u)
{
x->setlink(x->getlink());
}
temp = x->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
void Linked_list::check_empty()
{
if (head != NULL)
{
cout << "The list is empty.\n";
}
else
{
cout << "The list is not empty.\n";
}
}
linked_list.hpp
#include "node.hpp"
#ifndef linked_list_hpp
#define linked_list_hpp
class Linked_list
{
Node *head;
Node *tail;
int cnt;
public:
//default constructor creates empty linked list
Linked_list(void);
//Constructor that creates first node with values
Linked_list(data x);
//Inserts node at correct spot
void insert_node(data x);
//deletes specific node
void delete_node(int u);
//goes through whole list and prints out
void traverse(void);
//returns specific node
void retrieve_node(int u);
//checks if list is empty
void check_empty();
return_number();
};
#endif
node.hpp
#ifndef node_hpp
#define node_hpp
#include "node.hpp"
#include <string>
using namespace std;
struct data
{
int UPC;
string desc;
int quantity;
double cost;
int aisle;
};
class Node
{
data item;
Node *link;
public:
Node(void);
Node(data x);
void setlink(Node *ptr);
Node* getlink();
int getupc();
data get_structure();
bool compare_item(string i);
double processdata();
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
link = NULL;
}
Node::Node(data x)
{
item = x;
}
void Node::setlink(Node *ptr)
{
link = ptr;
}
Node* Node::getlink()
{
return link;
}
int Node::getupc()
{
return item.UPC;
}
data Node::get_structure()
{
return item;
}
bool Node::compare_item(string i)
{
if(i==item.desc)
{
return true;
}
else
{
return false;
}
}
double Node::processdata()
{
return item.cost*item.quantity;
}
main function
#include <iostream>
#include "node.cpp"
#include "linked_list.cpp"
using namespace std;
void fromfile(Linked_list &x);
void tofile(Linked_list &x);
int main(void)
{
Linked_list ll;
int x, y;
data a;
do
{
cout << "1.Add a grocery item\n" ;
cout << "2.Delete an item\n";
cout << "3.Retrieve an item\n";
cout << "4.Traverse the list forwards and print out all of the items\n";
cout << "5. Exit the program.\n";
cin >> x;
switch(x)
{
case 1:
cout << "Enter UPC code\n";
cin >> a.UPC;
cout << "Enter description(name of item)\n";
cin >> a.desc;
cout << "Enter quantity\n";
cin >> a.quantity;
cout << "Enter cost\n";
cin >> a.cost;
cout << "Enter aisle\n";
cin >>a.aisle;
ll.insert_node(a);
case 2:
cout << "Enter UPC of item you'd like to delete.\n";
cin >> y;
ll.delete_node(y);
case 3:
cout << "Enter UPC code.\n";
cin >> y;
ll.retrieve_node(y);
case 4:
ll.traverse();
case 5:
cout << "Bye!\n";
default:
cout << "Wrong choice, try again!\n";
}
}while (x != 5);
return 0;
}
Please help me out, this is due in 2 hours. I think I got it running somehow for a while and after the code performs in main, it just stop creating output after it reaches a linked_list function. Then, I can't enter anything afterwards.
The only thing not compiling is the linked_list.cpp, and I get a winmain error as well.

C++ Priority Queue Class with Linked List

I am having two issues with my c++ code (The test file is below):
I can't seem to figure out why its not breaking out of the while loop, when running, its stuck on the loop "7 versus 325".
So it should go into the next node of temp, which would be null, and then jump into the section where it adds it to the end of the queue. But its just looping and looping.
My second issue is with the the function I have commented out, queue1.back, whenever that is ran, it just errors out and gives what appears to be the address, but the .front() function works just fine.
The Test File I am working with is like this:
89 Alex
325 Rob
72 Joy
91 Bob
using namespace std;
class Person
{
friend class Pqueue;
public:
int priority;
string name;
};
class PQueue
{
friend class Person;
private:
//Structure for my linked list.
typedef struct node {
Person data;
struct node *next;
}Node, *NodePtr;
Node *head, *tail;
public:
//Prototype Functions
PQueue(void); //Initializer function
bool empty(void); //Test if empty
int size(void); //Return size
void enqueue(Person *); //Insert Node
void dequeue(void); //Remove Node
Person* front(void); //Access Next Node
Person* back(void); //Access last node
};
PQueue::PQueue()
{
head = NULL;
tail = NULL;
}
bool PQueue::empty(){
return (head == NULL);
}
void PQueue::enqueue(Person *myPerson){
NodePtr np = (NodePtr) malloc(sizeof(Node));
np->data = *myPerson;
np->next = NULL;
if(empty())
{
cout << "Making into creating the first node, of the linked list" <<endl;
head = np;
tail = np;
}
else { //Queue has more the one node
Node* temp = head;
if(np->data.priority > temp->data.priority) //If the priority is greater then the rest.
{
head = temp; //Saving my head pointer
head->data = np->data; //Assigning new Data to the head pointer
head->next = temp; //Assigning the rest of the linked list back into head.
cout << "Making into creating the first node again, having to reassign." <<endl;
}
else{
//Searching where to place the node.
while(temp->data.priority > np->data.priority) //Searching if the next priority is higher then the passed.
{
cout << "Inside the while loop: " << np->data.priority << " versus "<<temp->data.priority <<endl;
if(temp->next == NULL)
break;
temp = temp->next;
}
if(temp->next == NULL && np->data.priority < temp->data.priority) //Inserting at the end.
{
cout << "Making into creating the last node" <<endl;
tail->next = np;
cout << "Passing the function of creating the last node" <<endl;
}
else //Inserting into the middle of the function.
{
cout << "Inserting in the middle of the queue" <<endl;
np->next = temp->next;
temp->next = np;
}
}
}
}
void PQueue::dequeue(){
if(empty()){
cout << "\nAttempt to remove from an empty list." << endl;
exit(1);
}
Person hold = head->data;
NodePtr temp = head;
head=head->next;
if (head == NULL) tail = NULL;
free(temp);
}
Person* PQueue::front(){
//Person &temp = head->next->data;
//Person &temp = head->data;
Person &temp = head->data;
return &temp;
}
Person* PQueue::back(){
if(empty()){
cout << "\nNo entries in list." << endl;
exit(1);
}
Person &temp = tail->data;
return &temp;
}
int main() {
cout << "Starting main" << endl;
PQueue queue1; //Creating my queue.
cout << "Created Queue" << endl;
Person tempPerson;
ifstream inFile;
inFile.open("/tmp/temp");
cout << "going into while loop" << endl;
while (inFile >> tempPerson.priority >> tempPerson.name){
cout << "The priority is " << tempPerson.priority << " the name is " << tempPerson.name <<endl;
queue1.enqueue(&tempPerson);
}
//Testing Section, trying to get .front and .back to work.
Person *testPerson;
testPerson = queue1.front();
cout << "The TEST priority is " << testPerson->priority << " the TEST name is " << testPerson->name <<endl;
/**
Person *tailPerson;
testPerson = queue1.back();
cout << "The TEST priority is " << tailPerson->priority << " the TEST name is " << tailPerson->name <<endl;
**/
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
return 0;
}
When you add a new head entry to a non-empty list, you're mistakenly setting the next pointer to point right back at the node it's in, rather than setting it to point at the rest of the linked list like you intended.
head = temp; //Saving my head pointer
head->next = temp; //Assigning the rest of the linked list back into head.

Can not display stacks or Push

So I have a project for my C++ class and we are asked to create a library program using Stacks and Doubly Linked Lists. Now we cannot use the stack header file so everything from push, pop, display, etc. has to created by us.
I have the push function working, but the display function I cannot seem to get it to display more than just the lastNode stuct. When it tries to access previousNode, it crashes. Any ideas on what I'm doing wrong?
Also I can not get the pop function to work either. The program crashes as well when it runs.
void pushBook(BookStack *bkStack, BookNode *bkNode)
{
if(isEmpty(bkStack))
{
bkStack->lastNode = bkNode;
bkStack->lastNode->previousNode = NULL;
}
else
{
bkStack->lastNode->previousNode = bkStack->lastNode;
bkStack->lastNode = bkNode;
}
}
BookNode *popBook(BookStack *bkStack)
{
BookNode *temp = new BookNode;
if(isEmpty(bkStack))
{
temp = bkStack->lastNode;
return temp;
}
else if(bkStack->lastNode->previousNode == NULL)
{
temp = bkStack->lastNode;
bkStack->lastNode = NULL;
return temp;
}else
{
temp = bkStack->lastNode->previousNode;
bkStack->lastNode->previousNode = NULL;
bkStack->lastNode = temp;
return temp;
}
}
void displayStackElements(BookStack *bkStack)
{
BookNode *nodePtr = new BookNode;
nodePtr = bkStack->lastNode;
if(isEmpty(bkStack))
{
cout << "Book stack is empty." << endl;
}
else
{
while(nodePtr != NULL)
{
cout << "\nBook Name: " << nodePtr->bk.name << endl;
cout << "Author Name: " << nodePtr->bk.authorName << endl;
cout << "Page Numbers: " << nodePtr->bk.pagesNumber << endl;
cout << "ISBN: " << nodePtr->bk.isbn << endl;
cout << endl;
nodePtr = bkStack->lastNode->previousNode;
}
}
}
bool isEmpty(BookStack *bkStack)
{
bool status;
if(bkStack->lastNode == NULL)
status = true;
else
status = false;
return status;
}
void addBook(BookStack *bkStack)
{
BookNode *bkNode = new BookNode;
cout << "\nEnter the book name: ";
getline(cin, bkNode->bk.name);
cout << "Enter the Author's Name: ";
getline(cin, bkNode->bk.authorName);
cout << "Enter the ISBN: ";
cin >> bkNode->bk.isbn;
cout << "Enter the page numbers: ";
cin >> bkNode->bk.pagesNumber;
pushBook(bkStack, bkNode);
}
void removeBook(BookStack *bkStack)
{
BookNode *removedNode = new BookNode;
removedNode = popBook(bkStack);
if(removedNode == NULL)
{
cout << "\nNo books to remove." << endl;
}else
{
cout << endl << removedNode->bk.name << " was removed." << endl;
}
}
(edit) Sorry about that here's the structs from the main header file
struct Book
{
int isbn;
string name;
string authorName;
int pagesNumber;
};
struct BookNode
{
Book bk;
BookNode *previousNode;
};
struct BookStack
{
BookNode *lastNode = NULL;
};
I haven't done c++ in a while so if any of the statement below are wrong, tell me so !
Here what I see :
In displayStackElements:
nodePtr = bkStack->lastNode->previousNode; should be nodePtr = nodePtr->previousNode; otherwise, you will always display the previousnode of lastnode of bkStack in an infinite loop !
I don't know why you do this everywhere:
BookNode *nodePtr = new BookNode;
nodePtr = bkStack->lastNode;
You don't need a new BookNode if you are assigning it right after it ! You are creating a new BookNode in memory and then overwrite the pointer. This is a memory leak. You can simply do this:
BookNode *nodePtr = bkStack->lastNode;
In your pop function, the last else code should be this. You want to pop out the lastnode, not the previous node of the current last node.
temp = bkStack->lastNode->previousNode;
BookNode *lastNode = bkStack->lastNode
bkStack->lastNode->previousNode = NULL;
bkStack->lastNode = temp;
return lastNode;
In your push function, you are setting the previousNode of last node but after that, you were overwriting the lastNode with the node passed in parameter. Your list became broken because the lastNode->previousNode will always be emtpy. The else statement should be this.
bkNode->previousNode = bkStack->lastNode;
bkStack->lastNode = bkNode;
As you don't show the BookNode class definition or its constructor, I can only assume that you forget to clear the nodes previousNode pointer, which means that after you add the second second node then bkStack->lastNode->previousNode will be an uninitialized pointer.
Dereferencing uninitialized pointers leads to undefined behavior.