0

Im having some trouble putting together a linked list implementation of a queue. I'm getting a segmentation fault, which I believe is due to my empty() function because in an attempt to fix my empty() function, I made it determine empty based on (current_size == 0) instead of (front_p == NULL). Based on the test program that I ran enqueue, dequeue, etc all work properly. Even empty() works to check if the queue is empty() at the beginning of the program. But after dequeueing everything, the final check for empty() fails; hence why I decided to make the above changes to my empty() function. Any ideas as to why im getting this error at runtime? I seem to be incrementing/decrementing current_size properly.

#include <iostream>
#include <cstring>
#include "queue.h"
using namespace std;

queue::queue(){
    back_p = NULL;
    front_p = NULL;
}

void queue::enqueue(int item){
    if(empty()){
        front_p = new node(item, NULL);
        back_p = front_p;
        current_size++;
    }
    else{
        back_p -> next = new node(item, back_p);
        back_p = back_p -> next;
        current_size++;
    }
}

int queue::dequeue(){
    node * temp;
    if(empty()){
        cout << "queue is empty" << endl; 
        return 0;
    }
    else{
        int num = front_p -> data;
        temp = front_p;
        front_p = front_p -> next;
        delete temp;
        return num;
        current_size--;
    }
}

int queue::remove(int item){
    node * cursor;
    node * temp2;
    int counter = 0;
    if(empty()){
        cout << "queue is empty" << endl;
        return 0;
    }
    else{
        while(cursor->next != back_p){
            if(cursor->data == item){
                temp2 = cursor;
                cursor = cursor -> next;
                delete temp2;
                current_size--;
                counter++;
            }
            else{
                cursor = cursor -> next;
            }
        }
        return counter;
    }
}

int queue::front(){return front_p -> data;}

bool queue::empty(){
    if(current_size == 0){return true;}
    else{return false;}
}

int queue::size(){return current_size;}

Any help would be appreciated. Thanks!

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by dx9_programmer
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.