To get the unique nodes from a list of edges in C, you can use a set data structure. Here's a sample code that demonstrates this:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// Structure to represent an edge
typedef struct {
    int node1;
    int node2;
} Edge;

// Function to compare two edges
bool compareEdges(const Edge *e1, const Edge *e2) {
    return (e1->node1 == e2->node1 && e1->node2 == e2->node2);
}

// Function to get unique nodes from a list of edges
void getUniqueNodes(const Edge *edges, int numEdges, int *uniqueNodes, int *numUniqueNodes) {
    // Create a set to store unique nodes
    int *nodeSet = (int *)malloc(numEdges * sizeof(int));
    int numNodes = 0;

    for (int i = 0; i < numEdges; i++) {
        bool node1Exists = false;
        bool node2Exists = false;

        for (int j = 0; j < numNodes; j++) {
            if (edges[i].node1 == nodeSet[j]) {
                node1Exists = true;
            }
            if (edges[i].node2 == nodeSet[j]) {
                node2Exists = true;
            }
        }

        if (!node1Exists) {
            nodeSet[numNodes] = edges[i].node1;
            numNodes++;
        }
        if (!node2Exists) {
            nodeSet[numNodes] = edges[i].node2;
            numNodes++;
        }
    }

    // Copy unique nodes to the output array
    for (int i = 0; i < numNodes; i++) {
        uniqueNodes[i] = nodeSet[i];
    }

    *numUniqueNodes = numNodes;

    // Free memory
    free(nodeSet);
}

int main() {
    Edge edges[] = {
        {1, 2},
        {2, 3},
        {3, 4},
        {2, 4},
        {4, 5},
        {5, 6},
        {6, 1}
    };

    int uniqueNodes[6];
    int numUniqueNodes;

    getUniqueNodes(edges, 7, uniqueNodes, &numUniqueNodes);

    printf("Unique nodes: ");
    for (int i = 0; i < numUniqueNodes; i++) {
        printf("%d ", uniqueNodes[i]);
    }
    printf("\n");

    return 0;
}

In this code, we define a structure Edge to represent an edge with two nodes. We also define a function compareEdges to compare two edges.

The getUniqueNodes function takes the list of edges, the number of edges, an array to store the unique nodes, and a pointer to store the number of unique nodes. It creates a set using an array nodeSet to store the unique nodes. It then iterates through the edges and checks if each node already exists in the set. If not, it adds the node to the set. Finally, it copies the unique nodes from the set to the output array.

In the main function, we define an array of edges and call the getUniqueNodes function to get the unique nodes. We then print the unique nodes to verify the result

C get unique nodes of edges with two nodes

原文地址: https://www.cveoy.top/t/topic/hPrn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录