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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -