C Complex Data Structures Tutorial

C programming allows you to work with complex data structures like linked lists, trees, and graphs. These structures are essential for managing and manipulating large sets of data.

1. Linked Lists

A linked list is a linear data structure where each element (node) contains data and a reference (or link) to the next node in the sequence.


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

struct Node {
    int data;
    struct Node* next;
};

void printList(struct Node* n) {
    while (n != NULL) {
        printf("%d -> ", n->data);
        n = n->next;
    }
    printf("NULL\n");
}
                

This example creates a simple linked list and prints the values stored in it.

2. Trees

A tree is a hierarchical data structure, with a root element and sub-elements (children). It is widely used in databases and file systems.


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

struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
};

void inorder(struct TreeNode* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}
                

This example demonstrates a basic binary tree with an inorder traversal.

3. Graphs

A graph is a collection of nodes and edges. It is a non-linear data structure, commonly used to represent networks, social connections, and relationships.


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

#define MAX 5

struct Graph {
    int adjMatrix[MAX][MAX];
};

void printGraph(struct Graph* g) {
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) {
            printf("%d ", g->adjMatrix[i][j]);
        }
        printf("\n");
    }
}
                

This example shows a graph represented by an adjacency matrix.

4. Conclusion

Complex data structures are crucial for handling large datasets efficiently. Mastering them allows you to solve more advanced programming challenges in C.

0 Interaction
1.6K Views
Views
44 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home