简体   繁体   中英

How to find a predecessor of a minimum element in a linked list implementation of a queue?

so i want to find a predecessor of a minimum element in a queue. I have used a linked list implementation of a queue. I have been able to find a minimum element in a queue, but i have no idea how to find a predecessor of a minimum element. For example lets say a queue consits of elements like: [5 3 1 4]. I need to find the element 3, as it is the predecessor of the minimum element which in this case is 1. Thanks in advance for any help.

Here's what I have done so far:

template <typename InfoType>
void LQueue <InfoType>::MinElementP() {
    Node *min = head;
    Node *h = head;
        
    while (h != 0){
        if (min->info > h->info){
            min->info = h->info;
        }
        h = h->next;
    }
    
    cout << "Minimum element (the smallest element) in this queue is : " << min->info << "\n";
}

I got it working now, i initialized a new pointer that points to the predecessor, just before the h= h->next;statement, so for example predecessor = h;

What type of variables have you created in node ? If it has a key in ascending order to keep track of your nodes, then you can get the key of predecessor by subtracting one from key of node with minimum value . Or you could create a double linked link list which points to previous element as well by making a pointer named previous in node type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM