Home > Blockchain >  delete a specific node in a grapgh adjacency list -directed graph
delete a specific node in a grapgh adjacency list -directed graph

Time:01-03

hi there I have this struct info

struct Graph
{
  // An array of pointers to Node to represent an adjacency list
  size_t nodes;
  struct Node *head[];
};

// Data structure to store adjacency list nodes of the graph
struct Node
{
  int dest, weight;
  struct Node *next;
};

I want to build a function that removes a specific node distance value my main function for calling the delete function will look like this>>

int main()
{
       .
       .
       .
      struct Graph *graph;
      Node_delete(graph,x);

       .
       .
       .
}

enter image description here
if (x==4) then the function will delete every node that contain the distance value of 4
if the node in the middle of the previous node will be connected to the next node
and if the node in the last node will be deleted and the previous node will point to null and so on...
so our graph result will look like this >>

enter image description here

any suggestions on how can I build the delete_node function?

CodePudding user response:

Let's say you have a global graph with your graph (as you don't have it as argument).

The function will return the number of deleted nodes.

You have to loop on all list with a simple for:

for (int i = 0; i < graph.nodes; i )

Then, if the first element should be removed you need to change the Node * into the head array. This is done with the while loop while (first && first->distance == distance)

Once you have delete the leading head, you can delete the other node with a while (n->next)

This will give something like:

int Node_delete(int distance) {
    int res = 0;
    for (int i = 0; i < graph.nodes; i  ) {
        Node *first = graph.nodes[i];
        Node *n = first;
        while (first && first->distance == distance) {
            first = first->next;
            free(n);
            res  ;
            n = first;
        }   
        while (n->next) {
            Node *next= n->next;
            if (next->distance == distance) {
                n->next = next->next;
                free(next);
                res  ;
            }
            n = n->next;
        }
        graph.head[i] = first;
    }
    return res;
}

CodePudding user response:

LOOP over head[]
   Step through list
      If "distance" ( however you decide to spell it ) = x
          set previous next to current next
          delete current
  • Related