vendredi 27 mars 2015

Segementation 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;
}



Aucun commentaire:

Enregistrer un commentaire