Cover Image for Self-referential structure in C
267 views

Self-referential structure in C

A self-referential structure in C is a structure that contains a pointer to an instance of the same structure type within itself. This concept is widely used in data structures like linked lists, trees, and graphs, where each element (node) of the data structure has a reference to another element of the same type.

Here’s an example of a self-referential structure for a singly linked list node:

C
#include <stdio.h>

// Define a self-referential structure for a singly linked list node
struct Node {
    int data;
    struct Node* next; // Pointer to the next node of the same type
};

int main() {
    // Create nodes and link them to form a linked list
    struct Node node1, node2, node3;
    node1.data = 10;
    node2.data = 20;
    node3.data = 30;

    node1.next = &node2;
    node2.next = &node3;
    node3.next = NULL; // The last node points to NULL, indicating the end of the list

    // Traverse and print the linked list
    struct Node* current = &node1; // Start from the first node

    printf("Linked List: ");
    while (current != NULL) {
        printf("%d -> ", current->data);
        current = current->next;
    }
    printf("NULL\n");

    return 0;
}

In this example:

  • We define a struct Node that contains an int data field and a pointer next to the next node of the same type (struct Node*).
  • We create three nodes (node1, node2, and node3) and assign integer values to their data fields.
  • We link the nodes together to form a singly linked list. node1 points to node2, node2 points to node3, and node3 points to NULL, indicating the end of the list.
  • We traverse and print the linked list, starting from node1 and following the next pointers until we reach a node with a NULL pointer, signifying the end of the list.

This is a basic example of a singly linked list using a self-referential structure. You can use similar principles to create more complex data structures like doubly linked lists, binary trees, and graphs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS