c - How to delete all nodes of same value from linklist/Queue -


i have been trying hard resolve yet not succeed have data structs follow (which complex simplifies discussion) :

typedef struct node{  struct node* next;   void* arg; }node_t;  typedef struct queue{ node_t* head; node_t* tail; }queue_t;  addq(queue_t*ptr , int data) {     queue_t* q = ptr;     node_t * n = malloc(sizeof(*n));      n->arg = data;     n->next = null;      if(null == q->head){        q->head = q->tail = n;        return ;     }     q->tail->next = n;     q->tail = q->tail->next; } 

now want delete node of same value ( have tried couple ways yet not succeed ) , consider sequence reference:

addq(q, 12); addq(q, 12); addq(q,  4); addq(q, 12); addq(q, 12); addq(q, 14); addq(q, 12); addq(q, 12); 

i want delete nodes value 12.

this solution got bit hairy double pointers, still it, doesn't have special case node (first vs rest) being checked. tried put enough comments in describe what's going on, it's still hard me follow @ first glance.

pseudocode..

queue * q; value = 12;  // double pointer can treat queue head , subsequent nodes same. //   because both pointers node.   // otherwise you'd have have code says if 1 you're removing  // first element of queue, adjust q->head, otherwise adjust node->next.   // lets not special case deletion. node ** node_ptr = &(q->head)  while (*node_ptr != null) {     if ((**node_ptr).arg == value) {         // store off matching node freed because otherwise we'd orphan         // when move thing pointing , we'd never able free         node * matched_node = *node_ptr;          // when find match, don't move node_ptr points, change value         // points to skip matched node , point 1 after (or null)         *node_ptr = matched_node->next;          free(matched_node);     } else {         // otherwise, nothing deleted, skip on node next one.         // remember, **node_ptr double dereference, we're @ node         // now, grab address of non-matching node's next value can         // potentially changed in next iteration         node_ptr = &((**node_ptr).next);     } } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -