Reputation: 279
I apologize that this is a rather long question...I am making a specific function for a linked list implementation of a queue. This function is called int Queue::modify(int item)
, where it takes in an integer, and if this integer occurs in the queue more than once, I have to delete all occurrences of the integer from the queue except the first one.
So for example, if my queue looks like [1,2,2,2,2,2,3] and the item is 2, the resulting queue would look like [1,2,3]. My code, however, is outputting [1,2,2,2,3].
Below is my code, and below my code, is my explanation on how I tried to implement this:
int Queue::modify(int item){
node* curr = front;
node* temp;
int counter = 0;
if (curr == NULL){
return 0;
}
//checking to see if first instance of queue is == item
if (curr->data == item){
counter++;
}
//checking to see if instances after first instance of queue is == item
while (curr != NULL){
if (curr->next != NULL){
temp = curr->next;
if (temp->data == item){
counter ++;
if (counter > 1){
if (curr->next->next != NULL){
curr->next = curr->next->next; //I think something is wrong here??
}
delete temp;
}
}
curr = curr->next;
}
//this is for the last instance of the queue, so curr->next == NULL
else{
if (curr->data == item){
counter++;
if (counter > 1){
delete curr;
curr = NULL;
}
else
curr = curr->next; //so curr should be NULL now
}
else
curr = curr->next; //so curr should be NULL now
}
}
return counter;
}
So basically, what I tried was having temp = curr->next
so that if curr->next->data == item
, then I can have curr's next pointer point to the node after temp so that the list is still linked, curr->next = curr->next->next
, and then delete temp as shown in the wonderfully illustrated diagram below:
I have a feeling that I'm brain farting and that curr->next = curr->next->next
is not correct...thank you in advance for any suggestions on what's wrong with my code! Also, this IS HOMEWORK so although I would absolutely love a full code solution, please refrain from posting full code solutions....thank you! :D
Upvotes: 2
Views: 362
Reputation: 6407
I suppose, that condition
if (curr->next->next != NULL){
not needed. You can make copy
curr->next = curr->next->next;
in any case
Upvotes: 1
Reputation: 206567
In these lines,
if (counter > 1){
if (curr->next->next != NULL){
curr->next = curr->next->next; //I think something is wrong here??
}
You are skipping nodes. The surrounding code needs to be:
if (temp->data == item)
{
counter ++;
if (counter > 1){
curr = temp->next;
delete temp;
}
}
else
{
curr = curr->next;
}
Upvotes: 1