I am having a hard time making a pop function for a priority queue for an undero
ID: 3703948 • Letter: I
Question
I am having a hard time making a pop function for a priority queue for an underordered linked list implimentation. How do i construct the code to pop the lowest integer in the queue as a priority?
void pop(){
if( head == NULL){ //check if the stack is empty
//use two pointers to accomplish the task
cout<<"the queue is empty"<<endl;
if ( head == end ){
head = end = NULL; //the the front and the end pointer equal then it is empty
}
}
while (head != NULL){
//have a temp pointer point to the end so that the end can be popped instead of the front
// Node *temp = end; //make temp point to head
//end = temp->next; //make end point skip over that element and point to the next one
//count --; //count how many times the head moves through the list
//cout<<"poped "<<temp->data<<endl;
int min = INT_MAX;
// Check loop while head not equal to NULL
// If min is greater then head->data then
// assign value of head->data to min
// otherwise node point to next node.
if (min > head->data){
min = head->data;
head = head->next;
cout <<"popped"<<min<<endl;
}
}}
Explanation / Answer
If you still have any doubts, please give me comment...
void pop()
{
if (head == NULL)
{ //check if the stack is empty
//use two pointers to accomplish the task
cout << "the queue is empty" << endl;
if (head == end)
{
head = end = NULL; //the the front and the end pointer equal then it is empty
}
}
else{
int min = INT_MAX;
//declaring temp node to traversal from head to end, popNode to remove min node and prev link to another
Node *temp = head, *popNode =NULL, *prev =NULL;
//traversing from head to end for find min value and min popNode
while (temp != NULL)
{
//checking temp->data is min or not
if (min > temp->data)
{
//if min assign to min
min = temp->data;
//assigning popNode
popNode = temp;
}
//storing previous
prev = temp;
//move to next node
temp = temp->next;
}
//if popNode is head then move head to head->next
if(popNode == head){
head = popNode->next;
}
//if popNode is end then assinging NULL to prev->next node
else if(popNode->next = NULL){
prev->next = NULL;
}
//if popNode is somewhere middle in list then bypassing node
else{
prev->next = popNode->next;
}
//popping popNode;
free(popNode); //if cpp use "delete popNode"
cout << "popped" << min << endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.