Implementing a Queue Class, Segmentation Fault? - c++

I'm attempting to implement a Queue Class (using a Node struct, and Queue class).
I'm getting a segmentation fault and my eyes are failing me, I can't seem to find it.
My pushBack won't work and I'm pretty sure my popFront probably doesn't work. I'm just hoping somebody is able to give me a good push in the right direction!
Also, if you haven't been able to figure it out yet. I'm clearly very new to C++.
#include <iostream>
using namespace std;
struct Node {
int data;
Node* link;
};
class Queue {
public:
Queue();
~Queue();
void pushBack(int d);
bool popFront();
bool isEmpty();
void displayQueue();
private:
Node* back;
Node* front;
};
Queue::Queue() {
back = NULL;
front = NULL;
}
Queue::~Queue() {
while (!isEmpty()) {
popFront();
}
}
void Queue::pushBack(int d) {
Node* temp;
if (temp == NULL) {
return;
} else {
temp->link = NULL;
if (back == NULL) {
back = temp;
front = temp;
} else {
front->link = temp;
front = temp;
}
}
}
bool Queue::popFront() {
if (front == NULL) {
return false;
} else {
Node* removeNode;
removeNode = front;
if (back == front) {
back = NULL;
front = NULL;
} else {
Node* previousFront = back;
while (previousFront->link != front) {
previousFront = previousFront->link;
}
front = previousFront;
front->link = NULL;
}
delete removeNode;
return true;
}
}
bool Queue::isEmpty() {
return (back == NULL);
}
void Queue::displayQueue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
} else {
Node *current;
current = back;
cout << endl << "-- BACK -- ";
while (current != NULL) {
cout << current->data << " ";
current = current->link;
}
cout << "-- FRONT --" << endl << endl;
}
}
int main(){
Queue q;
q.displayQueue();
q.pushBack(20);
q.pushBack(30);
q.displayQueue();
q.pushBack(40);
q.pushBack(12);
q.displayQueue();
q.popFront();
q.displayQueue();
return 0;
}

There is at least one major issue, in pushBack you are using temp without initializing it:
void Queue::pushBack(int d)
{
Node* temp;
if (temp == NULL) {
^^^^
Compiling with warnings turned on would have helped you here, using the -Wall flag with gcc would have given you the following warning:
warning: 'temp' is used uninitialized in this function [-Wuninitialized]
if (temp == NULL) {
^
Using a variable an unintialized automatic variable like this is undeined behavior which means the behavior of your program is unpredictable. Also see Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++1y? for reference.
What you probably meant to do was something like this:
Node* temp = new Node();
temp->data = d ;
Although setting up a constructor for Node would be better.

you cannot set a variable like this: temp->link = NULL;

Related

Unhandled exception thrown: read access violation. "this" was 0x8 - Using Shared_ptr

Node.h
#pragma once
#include <iostream>
#include<memory>
class Node
{
public:
Node();
Node(int k, int d);
int key;
int data;
std::shared_ptr<Node> next;
std::shared_ptr<Node> previous;
//Node* next;
//Node* previous;
};
doubleLinkedList.h
#pragma once
/*! \class Double Linked List
\brief A double linked list data structure
*/
#include <iostream>
#include "../Node.h"
#include <string>
#include<memory>
class DoubleLinkedList : public Node
{
private :
std::shared_ptr<Node> head; //Node* head;
std::shared_ptr<Node> temp; //Node* temp;
std::shared_ptr<Node> mypointer; //Node* ptr;
std::shared_ptr<Node> nextNode;
std::shared_ptr<Node> prevNode;
public :
DoubleLinkedList();
DoubleLinkedList(std::shared_ptr<Node> n);
std::shared_ptr<Node> checkNodeExsits(int k); //Node*
void addNodeToFront(std::shared_ptr<Node> n); //Node*
void addNodeToEnd(std::shared_ptr<Node> n); //Node*
void addNodeAfter(int k, std::shared_ptr<Node> n); //Node*
void UpdateNode(int k , int d);
void deleteNode(int k);
void printList();
void printInfo(std::string Info);
};
Node.cpp
#include "Node.h"
#include <iostream>
Node::Node()
{
key = 0;
data = 0;
next = nullptr;
previous = nullptr;
}
Node::Node(int k, int d)
{
key = k;
data = d;
}
doubleLinkedList.cpp
#include <iostream>
#include "include\doubleLinkedList.h"
DoubleLinkedList::DoubleLinkedList()
{
head = nullptr;
}
DoubleLinkedList::DoubleLinkedList(std::shared_ptr<Node> n)
{
head = n;
}
std::shared_ptr<Node> DoubleLinkedList::checkNodeExsits(int k)
{
temp = nullptr;
mypointer = head;
while (mypointer != nullptr) {
if (mypointer -> key == k) {
temp = mypointer;
}
mypointer = mypointer-> next;
}
return temp;
}
void DoubleLinkedList::addNodeToFront(std::shared_ptr<Node> n)
{
if (checkNodeExsits(n->key) != nullptr)
{
printInfo("Node Already exist with key Number ");
}
else {
if (head == nullptr) {
head = n;
printInfo("Node Added as Head Node");
}
else {
head->previous = n;
n->next = head;
head = n;
printInfo("Node Added To The Begining");
}
}
}
void DoubleLinkedList::addNodeToEnd(std::shared_ptr<Node> n)
{
if (checkNodeExsits(n->key) != nullptr)
{
printInfo("Node Already exist with key Number");
}
else {
if (head == nullptr)
{
head = n; // if there isnt any node in the list.
printInfo("Node Has Been Added As Head Node");
}
else {
mypointer = head;
while (mypointer ->next != nullptr)
{
mypointer = mypointer->next;
}
mypointer->next = n;
n->previous = mypointer;
printInfo("Node Has Been Added To The End");
}
}
}
void DoubleLinkedList::addNodeAfter(int k, std::shared_ptr<Node> n)
{
mypointer = checkNodeExsits(k);
if (mypointer == nullptr) {
printInfo("No Node Exists With The Key Value");
}
else {
if (checkNodeExsits(n -> key) != nullptr) {
printInfo("Node Already exist with key Number");
}
else {
nextNode = mypointer-> next;
// inserting at the end
if (nextNode == nullptr) {
mypointer-> next = n;
n -> previous = mypointer;
printInfo("Node Inserted at the END");
}
//inserting in between
else {
n -> next = nextNode;
nextNode -> previous = n;
n -> previous = mypointer;
mypointer-> next = n;
printInfo("Node Inserted in Between");
}
}
}
}
void DoubleLinkedList::UpdateNode(int k, int d)
{
mypointer = checkNodeExsits(k);
if (mypointer != nullptr) {
mypointer-> data = d;
std::cout << "Node Data Updated Successfully" << std::endl;
}
else {
std::cout << "Node Doesn't exist with key value : " << k << std::endl;
}
}
void DoubleLinkedList::deleteNode(int k)
{
mypointer = checkNodeExsits(k);
if (mypointer == nullptr) {
std::cout << "No node exists with key value: " << k << std::endl;
}
else {
if (head -> key == k) {
head = head -> next;
std::cout << "Node UNLINKED with keys value : " << k << std::endl;
}
else {
nextNode = mypointer-> next;
prevNode = mypointer-> previous;
// deleting at the end
if (nextNode == nullptr) {
prevNode -> next = nullptr;
std::cout << "Node Deleted at the END" << std::endl;
}
//deleting in between
else {
prevNode -> next = nextNode;
nextNode -> previous = prevNode;
std::cout << "Node Deleted in Between" << std::endl;
}
}
}
}
void DoubleLinkedList::printList()
{
if (head == nullptr) {
std::cout << "No Nodes in Doubly Linked List";
}
else {
std::cout << std::endl << "Doubly Linked List Values : ";
temp = head;
while (temp != nullptr) {
std::cout << "[Key: " << temp->key << ", Data: " << temp->data << "] <___> " << std::endl;
temp = temp -> next;
}
}
}
void DoubleLinkedList::printInfo(std::string Info)
{
std::cout << Info << std::endl;
}
main.cpp
#include <iostream>
#include "../include/doubleLinkedList.h"
#include"../Node.h"
void Print(std::string info)
{
std::cout << info << std::endl;
}
int main() {
DoubleLinkedList myNode;
//Node* newNode = new Node(2,7);
std::shared_ptr<Node> newNode = std::make_shared<Node>(2, 7); // enter key number and data number
std::shared_ptr<Node> newNode1 = std::make_shared<Node>(3, 9);// enter key number and data number
newNode->key;
newNode->data;
myNode.addNodeToFront(newNode);
newNode->key;
newNode->data;
myNode.addNodeAfter(2, newNode1); // enter the key number of existing node and then to add new key number and new data
myNode.printList();
system("pause");
return 0;
}
The error I'm getting is:
unhandled exception thrown: read access violation. "this" was 0x8
To elaborate -
( Access violation reading location 0x0000000000000010. Unhandled exception thrown: read access violation).
So, the code would work when I use raw pointers. The only thing I can deduce from this is that there's a chain of shared pointers in the method of void DoubleLinkedList::addNodeAfter() nextNode = mypointer-> next;
or that shared pointers can't have nullptr assigned to it.
I'm clueless as to why this is happening.
Let's take a walk through addNodeAfter
mypointer = checkNodeExsits(k);
We've checked to make sure value k exists in the list and gotten a pointer to it if it does. If it doesn't, we get a null pointer.
if (mypointer == nullptr) {
Tests whether or not k was found. Let's assume it was, mypointer isn't null, and we enter the else
else {
if (checkNodeExsits(n -> key) != nullptr) {
Here we check to make sure the node we're inserting isn't a duplicate. Again let's take the else branch
else {
nextNode = mypointer-> next;
Should be safe, right? We know that mypointer was not null because we tested it earlier. But when we look... Holy smurf! The program crashed! It was null. How did it become null?
The answer lies in another question: Where did mypointer come from? It's not defined within this function, so it has wider scope. Turns out it is a DoubleLinkedList member variable. Is someone else messing with it? We don't have multiple threads, so it must be another function that was called by addNodeAfter.
That would have to be checkNodeExsits, so let's take a look at it.
std::shared_ptr<Node> DoubleLinkedList::checkNodeExsits(int k)
{
temp = nullptr;
mypointer = head; // well lookie here!
while (mypointer != nullptr) {
if (mypointer -> key == k) {
temp = mypointer;
}
mypointer = mypointer-> next; // and here!
}
return temp;
}
We can see that if the inserted node's value does not exist, thus putting us in the else case back in addNodeAfter where we're going to insert the new node, mypointer can only be null!
The overly broad scope of mypointer turns the member variable into a boobytrap. It needs to be a variable local to checkNodeExsits and addNodeAfter to prevent these functions from trashing the state of the functions that use them. This leads to questioning whether mypointer should be a member variable anywhere it is found. That leads to wondering about temp, nextnode and prevnode. They all sound like temporary holders of local state information. Likely the only DoubleLinkedList member that should be a member is head.
To fix: Remove the definition of mypointer from the class and resolve the compiler errors that result. If a use of mypointer can be easily replaced with a local variable, do so. For any that remain and are needing of longer-term storage for resuse, you'll have to get a bit more creative. Make the call on how long-lived and how wide a scope is necessary to get the behaviour you want and then give this new variable an appropriately descriptive name to help you remember the circumstances in which it should be used.
I recommend repeating this process for the other member variables except for head where the necessary scope and lifetime is obvious.
General rule of thumb: Keep the scope of variables as tight as possible. Only widen the scope of a variable if you absolutely need to reuse its state later, and if you find you must be very careful with it to ensure you don't cause unintended side-effects.

I made my own custom stack and want to know how is there a way to iterate through the stack in reverse

This is the interface file
#ifndef STACK_H
#define STACH_H
#include<iostream>
using namespace std;
class Stack
{
struct StackFrame{
char data;
StackFrame* next;
};
StackFrame* head;
public:
Stack();
void push(char);
char pop();
void empty();
bool check_empty();
void print();
//Note:This code prints the data in stack format !!!
~Stack();
};
#endif // !STACK_H
This is the implementation file
#include "Stack.h"
Stack::Stack():head(nullptr){}
void Stack::push(char c)
{
StackFrame* temp = new StackFrame;
temp->data = c;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
return;
}
temp->next = head;
head = temp;
}
char Stack::pop()
{
if (head == nullptr)
{
cerr << "There is nothing in the stack to pop at the moment!!!" << endl;
return '\0';
}
StackFrame* holder = head;
char temp_chr = holder->data;
head = head->next;
free(holder);
holder = nullptr;
return temp_chr;
}
void Stack::empty()
{
StackFrame* holder;
while(head!=nullptr)
{
holder = head;
head = head->next;
free(holder);
}
holder = nullptr;
head = nullptr;
}
bool Stack::check_empty()
{
return head==nullptr;
}
void Stack::print() {
if (head == nullptr)
{
cerr << "Nothing in stack at the moment :( " << endl;
return;
}
StackFrame* holder = head;
while (holder != nullptr)
{
cout << holder->data;
holder = holder->next;
}
cout << endl;
}
Stack::~Stack()
{
empty();
}
This is the application file
#include"Stack.h"
#include<string>
int main()
{
int num;
string push;
Stack st;
cout << "Enter your name = ";
getline(cin, push);
for (int i = 0; i < push.length(); i++)
{
st.push(push[i]);
}
st.print();
cout << "How many times do you want to pop? = ";
cin >> num;
for (int i = 0; i < num; i++)
{
st.pop();
}
st.print();
return EXIT_SUCCESS;
}
Can someone help me out on how to reverse iterate in this stack class which i made myself using the concept of linked list, i googled a bit and got the gist of things to use tail , Can someone elaborate another way if possible please or share a link to a site. It will help me out later a lot when i start working on binary trees and if i ever need to reverse iterate in the binary tree nodes.
First of all as mentioned above, stack is LIFO data structure and thus should use another data structure for that purpose.
Second, you can use second stack and copy data over to new stack, which is expensive.
Third option would be to go from the top and kip a track and store pointer to the previous node and to the pointer that point to the previous of previous node. Something like this:
struct reverseStack {
StackFrame* node;
reverseStack* previousPointer;
reverseStack (StackFrame* n, ReverseStack* p) :
node (n), previousPointer(p) { }
}
than using simple for loop you create pointer to the top, and go to the next and store that info into this structure. In your code you have something like this:
reverseStack top (nullptr, topFrame);
StackFrame currentFrame = top->next();
ReverseStack current; = top;
while (currentFrame != nullptr) {
// alghoritm for linking previous nodes.
}
I think you should add a second Stack object rather than a second list.
Recursive algorithm would have worked fine (use the recursive call stack as your "reverse" stack).
void Stack::print(StackFrame *pCurr) {
if (pCurr != nullptr)
{
print(pCurr->Next);
cout << pCurr->ch;
}
}
void Stack::print() {
if (head == nullptr)
{
cerr << "Nothing in stack at the moment :( " << endl;
return;
}
print(head);
cout << endl;
}

I am getting a breakpoint and i do not know why

I am trying to implement a priority Queue by using a linked list in c++. However, when I run the program it triggers a breakpoint within "priorityQLinkedList::dequeue()" method. Can someone tell why this is the case and give me suggestions on how to fix it?
Code:
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
struct DAT
{
int id;
char fullname[50];
double savings;
};
struct NODE
{
DAT data;
NODE *N;
NODE *P;
NODE(const int i, const char *f, const double s)
{
data.id = i;
strcpy_s(data.fullname, f);
data.savings = s;
N = NULL;
P = NULL;
}
};
class priorityQLinkedList
{
private:
NODE *front;
NODE *back;
public:
priorityQLinkedList() { front = NULL; back = NULL; }
~priorityQLinkedList() { destroyList(); }
void enqueue(NODE *);
NODE* dequeue();
void destroyList();
};
void priorityQLinkedList::enqueue(NODE *n)
{
if (front == NULL) {
front = n;
back = n;
}
else {
NODE *temp = front;
if (n->data.id > temp->data.id)
{
front->P = n;
n->N = front;
front = n;
}
else
{
//search for the posistion for the new node.
while (n->data.id < temp->data.id)
{
if (temp->N == NULL) {
break;
}
temp = temp->N;
}
//New node id's smallest then all others
if (temp->N == NULL && n->data.id < temp->data.id)
{
back->N = n;
n->P = back;
back = n;
}
//New node id's is in the medium range.
else {
temp->P->N = n;
n->P = temp->P;
n->N = temp;
temp->P = n;
}
}
}
}
NODE* priorityQLinkedList::dequeue()
{
NODE *temp;
//no nodes
if (back == NULL) {
return NULL;
}
//there is only one node
else if (back->P == NULL) {
NODE *temp2 = back;
temp = temp2;
front = NULL;
back = NULL;
delete temp2;
return temp;
}
//there are more than one node
else {
NODE *temp2 = back;
temp = temp2;
back = back->P;
back->N = NULL;
delete temp2;
return temp;
}
}
void priorityQLinkedList::destroyList()
{
while (front != NULL) {
NODE *temp = front;
front = front->N;
delete temp;
}
}
void disp(NODE *m) {
if (m == NULL) {
cout << "\nQueue is Empty!!!" << endl;
}
else {
cout << "\nID No. : " << m->data.id;
cout << "\nFull Name : " << m->data.fullname;
cout << "\nSalary : " << setprecision(15) << m->data.savings << endl;
}
}
int main() {
priorityQLinkedList *Queue = new priorityQLinkedList();
NODE No1(101, "Qasim Imtiaz", 567000.0000);
NODE No2(102, "Hamad Ahmed", 360200.0000);
NODE No3(103, "Fahad Ahmed", 726000.0000);
NODE No4(104, "Usmaan Arif", 689000.0000);
Queue->enqueue(&No4);
Queue->enqueue(&No3);
Queue->enqueue(&No1);
Queue->enqueue(&No2);
disp(Queue->dequeue());
disp(Queue->dequeue());
disp(Queue->dequeue());
disp(Queue->dequeue());
disp(Queue->dequeue());
delete Queue;
return 0;
}
One problem which stands out in your dequeue() method is that you are calling delete on a NODE pointer, and then attempting to return this deleted pointer to the caller. This could cause an error either in dequeue() itself, or certainly in the caller who thinks he is getting back a pointer to an actual live NODE object.
One potential fix would be to create a copy of the NODE being dequeued. You would still remove the target from your list, but the caller would then be returned a valid pointer, which he could free later.
NODE* priorityQLinkedList::dequeue()
{
NODE *temp;
// no nodes
if (back == NULL) {
return NULL;
}
NODE *temp2 = back;
temp = new NODE(temp2->data.id, temp2->data.fullname, temp2->data.savings);
// there is only one node
else if (back->P == NULL) {
front = NULL;
back = NULL;
delete temp2;
return temp;
}
// there are more than one node
else {
back = back->P;
back->N = NULL;
delete temp2;
return temp;
}
}
You're deleting pointers in dequeue that priorityQLinkedList does not own, so you don't know if it is safe to delete them.
In this case, they are not since the node pointers passed to enqueue are addresses of local, stacked based variables and have not been allocated by new. (There's also the already mentioned problem of deleting a pointer then returning it, which is Undefined Behavior.)
The fix for the code as shown is to remove the calls to delete in dequeue. However, if changes are made so that the nodes passed to enqueue are dynamically allocated, you'll need to add something to handle that.
1.First change strcpy_s to strcpy is struct NODE.
2.Instead of Delete(temp2) use temp2--.
//no nodes
if (back == NULL) {
return NULL;
}
//there is only one node
else if (back->P == NULL) {
NODE *temp2 = back;
temp = temp2;
front = NULL;
back = NULL;
temp2--;
return temp;
}
//there are more than one node
else {
NODE *temp2 = back;
temp = temp2;
back = back->P;
back->N = NULL;
temp2--;
return temp;
}
I hope this will resolve the problem.

Basic Binary Tree Program c++

So I have been learning all about Binary Trees and decided to write a simple program to demonstrate to myself that I can implement my knowledge into working code. All I am trying to do with this code is add 4 numbers into a binary tree and output the numbers in order from least to greatest. Although, I did run into a problem with my code. When i run the code, Visual Studio breaks it at lines 29 and 59. I believe the problem has to do with the recursive function addLeaf but maybe its something else. Any advise, solutions, or input would be greatly appreciated.!
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* root = NULL;
node* createLeaf(int data)
{
node* n = new node;
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void addLeaf(int data)
{
node* curr = root;
//If tree is empty, create first node
if(root == NULL)
{
root = createLeaf(data);
}
//Left(Less than)
else if(data < curr->data)
{
//Check for curr->left
if(curr->left != NULL)
{
addLeaf(data);
}
else //Adds node to left if null
{
curr->left = createLeaf(data);
}
}
//Right(greater than)
else if(data > curr->data)
{
//Check for curr->right
if(curr->right != NULL)
{
addLeaf(data);
}
else //Adds node if right is Null
{
curr->right = createLeaf(data);
}
}
else
{
cout << "The data " << data << " has already been received\n";
}
}
void printTree(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
printTree(Ptr->left);
}
cout << Ptr->data << " ";
if(Ptr->right != NULL)
{
printTree(Ptr->right);
}
cout << Ptr->data << " ";
}
else
{
cout << "The Tree is empty\n";
}
}
int main()
{
int data[4] = {1, 7, 5, 4};
node* Ptr = root;
for(int i = 0; i < 4; i++)
{
addLeaf(data[i]);
}
printTree(Ptr);
system("PAUSE");
return 0;
}
one problem I can spot:
void addLeaf(int data)
{
node* curr = root;
.....
//Check for curr->left
if(curr->left != NULL)
{
addLeaf(data);
}
your so-called recursion did nothing. It only keep on calling addLeaf function, and the function keep on checking if root's left is not null and in turn call the addLeaf again.
Refactor all your code. Don't use any global variable. Make sure you passed correct parameters (e.g. you should pass the next level node to addLeaf)
The addleaf function is going to run infinitely. You only keep adding to the root without any check.
You assign Ptr to root, but then using new, assign it to some new address in memory, which the root does not point to.
You have to pass Ptr by reference to addLeaf, otherwise changes will be made to its copy which is destroyed as addLeaf terminates.
printTree prints the current node value twice (a copy paste error?)
Here is the complete code :
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct node
{
int data;
node* left;
node* right;
};
node* root = NULL;
node* createLeaf(int data)
{
node* n = new node;
n->data = data;
n->left = NULL;
n->right = NULL;
return n;
}
void addLeaf(node* &curr, int data)
{
//If tree is empty, create first node
if(curr == NULL)
{
curr = createLeaf(data);
}
//Left(Less than)
else if(data < curr->data)
{
addLeaf (curr->left, data);
}
//Right(greater than)
else if(data > curr->data)
{
addLeaf(curr->right, data);
}
else
{
cout << "The data " << data << " has already been received\n";
}
}
void printTree(node* Ptr)
{
if(root != NULL)
{
if(Ptr->left != NULL)
{
printTree(Ptr->left);
}
cout << Ptr->data << " ";
if(Ptr->right != NULL)
{
printTree(Ptr->right);
}
}
else
{
cout << "The Tree is empty\n";
}
}
int main()
{
int data[4] = {1, 7, 5, 4};
for(int i = 0; i < 4; i++)
{
addLeaf(root, data[i]);
}
printTree(root);
system("PAUSE");
return 0;
}

Segmentation fault in queue program when using push

Im getting a segmentation fault when i try to push elements into the queue, im not an expert working with queues so i dont recognize where the problem is.
I have been searching for the solution to this problem and even though people get similar problems i didnt help me fix my problem.
Here is the code:
(I used the debug option in Dev-c ++ 5.9.2 and it told me the line "temp->link = NULL;" is causing the problem but i have no idea how to fix it)
#include <iostream>
using namespace std;
struct Node {
int data;
Node* link;
};
class Queue {
public:
Queue();
~Queue();
void pushBack(int d);
bool popFront();
bool isEmpty();
void displayQueue();
private:
Node* back;
Node* front;
};
Queue::Queue() {
back = NULL;
front = NULL;
}
Queue::~Queue() {
while (!isEmpty()) {
popFront();
}
}
void Queue::pushBack(int d) {
Node* temp;
if (temp == NULL) {
return;
} else {
temp->link = NULL; <========== This is where is get the error
if (back == NULL) {
back = temp;
front = temp;
} else {
front->link = temp; <===== here too
front = temp;
}
}
}
bool Queue::popFront() {
if (front == NULL) {
return false;
} else {
Node* removeNode;
removeNode = front;
if (back == front) {
back = NULL;
front = NULL;
} else {
Node* previousFront = back;
while (previousFront->link != front) {
previousFront = previousFront->link;
}
front = previousFront;
front->link = NULL;
}
delete removeNode;
return true;
}
}
bool Queue::isEmpty() {
return (back == NULL);
}
void Queue::displayQueue() {
if (isEmpty()) {
cout << "Queue is empty!" << endl;
} else {
Node *current;
current = back;
cout << endl << "-- BACK -- ";
while (current != NULL) {
cout << current->data << " ";
current = current->link;
}
cout << "-- FRONT --" << endl << endl;
}
}
int main(){
Queue q;
q.displayQueue();
q.pushBack(20);
q.pushBack(30);
q.displayQueue();
q.pushBack(40);
q.pushBack(12);
q.displayQueue();
q.popFront();
q.displayQueue();
return 0;
}
You have to know that when you add a new
node to the list you constructed, you need to allocate a dynamic
location for the new node and then add it to the list -queue-;
second thing : when the back is pointing already at some node in the link
you need to make the new node points at the node the back was pointing at,
then make the back pointer points at the new node .
the new function (pushBack) bacomes :
void Queue::pushBack ( int d ) {
Node* temp = new Node;
temp->data = d;
temp->link = NULL;
if (back == NULL) {
back = temp;
front = temp;
}
else {
temp->link = back;
back = temp;
}
}
You are creating a pointer to a node, but you have not created the node yet. (what everyone else has said)
change
Node* temp; - stack memory
To
Node *temp = new Node() - heap memory
im not an expert working with queues so i dont recognize where the problem is
Note that the problem has nothing to do with queues: The problem is understanding how the language works.
As Thornkey pointed out, you have a temp var in your pushBack function. It's a pointer, but it points to random data until you tell what to point at. When you follow the pointer, it could go anywhere and get a segfault or break some other part of your program.