Algorithm for creating a "relative" priority queue? (c/c++) -
i want make queue using linked lists. there numerous algorithms out there that. i'm curious in how make relative priority queue.
maybe there special name type of queue, don't know it, , haven't had luck googling solution.
anyways, let's have struct, represent node of list.
struct node { int value; node* next; }
if want create priority queue (where element least value first), when insert example 5 7 1 8 2, list should this:
1 -> 2 -> 5 -> 7 -> 8
it's not hard implement that. want - when insert first element, other elements should have value relative previous element. so, in example, list/queue contain following values:
1 -> 1 -> 3 -> 2 -> 1
i'm not sure how implement that? following idea applicable:
in node struct add field, represent original value. find position of node i'm inserting same way when creating ordinary linked list, , say
temp->value = temp->originalvalue - previous->originalvalue;
you need store data in each node, either relative priority, or "previous" pointer. since next node's relative priority needs updated whenever node removed (how without prev pointer?), suggest "previous" pointer:
struct node { int value; node* next; node* prev; }
then function can evaluate relative priority:
int relative_priority(node* node) { if (node == null) return 0; if (node->prev == null) return node->value; return node->value - node->prev->value; }
note i'm using c, you'll need replace null 0 c++
Comments
Post a Comment