The Wayback Machine - https://web.archive.org/web/20241127021921/https://www.geeksforgeeks.org/self-referential-structures/
Open In App

Self Referential Structures

Last Updated : 24 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-referential in nature

Example: 

CPP
struct node {
    int data1;
    char data2;
    struct node* link;
};

int main()
{
    struct node ob;
    return 0;
}
Java
// Define the 'Node' class
class Node {
    // Data members to store the data
    int data1;
    int data2;

    // Reference to the next node
    Node link;

    // Constructor to initialize the data members
    public Node(int data1, int data2)
    {
        this.data1 = data1;
        this.data2 = data2;
        this.link = null;
    }

    // Default constructor
    public Node()
    {
        this.data1 = 0;
        this.data2 = 0;
        this.link = null;
    }
}

// Main class to demonstrate the creation of Node instance
public class Main {
    public static void main(String[] args)
    {
        // Create an instance of the 'Node' class using the
        // default constructor
        Node ob = new Node();

        // Optionally, you can print the node's data to
        // verify
        System.out.println("Data1: " + ob.data1
                           + ", Data2: " + ob.data2);
    }
}
Python
class node:
    def __init__(self):
        self.data1 = 0
        self.data2 = ''
        self.link = None


if __name__ == '__main__':
    ob = node()
JavaScript
// Define the 'node' object
class node {
    constructor(data1, data2) {
        this.data1 = data1;
        this.data2 = data2;
        this.link = null;
    }
}
// Create an instance of the 'Node' object
let ob = new Node();

Output

In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer. 
An important point to consider is that the pointer should be initialized properly before accessing, as by default it contains garbage value.

Types of Self Referential Structures  

  1. Self Referential Structure with Single Link
  2. Self Referential Structure with Multiple Links


Self Referential Structure with Single Link: These structures can have only one self-pointer as their member. The following example will show us how to connect the objects of a self-referential structure with the single link and access the corresponding data members. The connection formed is shown in the following figure. 

Implementation:

C++
#include <stdio.h>

struct node {
    int data1;
    char data2;
    struct node* link;
};

int main()
{
    struct node ob1; // Node1

    // Initialization
    ob1.link = NULL;
    ob1.data1 = 10;
    ob1.data2 = 20;

    struct node ob2; // Node2

    // Initialization
    ob2.link = NULL;
    ob2.data1 = 30;
    ob2.data2 = 40;

    // Linking ob1 and ob2
    ob1.link = &ob2;

    // Accessing data members of  ob2 using ob1
    printf("%d", ob1.link->data1);
    printf("\n%d", ob1.link->data2);
    return 0;
}
Java
// java implementation of above approach
public class Main {
    static class Node {
        int data1;
        int data2;
        Node link;
    }

    public static void main(String[] args)
    {
        Node ob1 = new Node(); // Node1

        // Initialization
        ob1.link = null;
        ob1.data1 = 10;
        ob1.data2 = 20;

        Node ob2 = new Node(); // Node2

        // Initialization
        ob2.link = null;
        ob2.data1 = 30;
        ob2.data2 = 40;

        // Linking ob1 and ob2
        ob1.link = ob2;

        // Accessing data members of  ob2 using ob1
        System.out.println(ob1.link.data1);
        System.out.println(ob1.link.data2);
    }
}
// This code is implemented by Chetan Bargal
Python
class node:
    def __init__(self):
        self.data1=0
        self.data2=0
        self.link=None

if __name__ == '__main__':
    ob1=node() # Node1

    # Initialization
    ob1.link = None
    ob1.data1 = 10
    ob1.data2 = 20

    ob2=node() # Node2

    # Initialization
    ob2.link = None
    ob2.data1 = 30
    ob2.data2 = 40

    # Linking ob1 and ob2
    ob1.link = ob2

    # Accessing data members of  ob2 using ob1
    print(ob1.link.data1)
    print(ob1.link.data2)
C#
using System;

public class MainClass {
    public class Node {
        public int data1;
        public int data2;
        public Node link;
    }

    public static void Main(string[] args)
    {
        Node ob1 = new Node(); // Node1

        // Initialization
        ob1.link = null;
        ob1.data1 = 10;
        ob1.data2 = 20;

        Node ob2 = new Node(); // Node2

        // Initialization
        ob2.link = null;
        ob2.data1 = 30;
        ob2.data2 = 40;

        // Linking ob1 and ob2
        ob1.link = ob2;

        // Accessing data members of  ob2 using ob1
        Console.WriteLine(ob1.link.data1);
        Console.WriteLine(ob1.link.data2);
    }
}
JavaScript
class node {
  constructor() {
    this.data1 = 0;
    this.data2 = 0;
    this.link = null;
  }
}

// Create node1
let ob1 = new node();

// Initialization
ob1.link = null;
ob1.data1 = 10;
ob1.data2 = 20;

// Create node2
let ob2 = new node();

// Initialization
ob2.link = null;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2
ob1.link = ob2;

// Accessing data members of ob2 using ob1
console.log(ob1.link.data1);
console.log(ob1.link.data2);

Output
30
40

Self Referential Structure with Multiple Links: Self referential structures with multiple links can have more than one self-pointers. Many complicated data structures can be easily constructed using these structures. Such structures can easily connect to more than one nodes at a time. The following example shows one such structure with more than one links.
The connections made in the above example can be understood using the following figure. 
 

Implementation:

CPP
#include <stdio.h>

struct node {
    int data;
    struct node* prev_link;
    struct node* next_link;
};

int main()
{
    struct node ob1; // Node1

    // Initialization
    ob1.prev_link = NULL;
    ob1.next_link = NULL;
    ob1.data = 10;

    struct node ob2; // Node2

    // Initialization
    ob2.prev_link = NULL;
    ob2.next_link = NULL;
    ob2.data = 20;

    struct node ob3; // Node3

    // Initialization
    ob3.prev_link = NULL;
    ob3.next_link = NULL;
    ob3.data = 30;

    // Forward links
    ob1.next_link = &ob2;
    ob2.next_link = &ob3;

    // Backward links
    ob2.prev_link = &ob1;
    ob3.prev_link = &ob2;

    // Accessing  data of ob1, ob2 and ob3 by ob1
    printf("%d\t", ob1.data);
    printf("%d\t", ob1.next_link->data);
    printf("%d\n", ob1.next_link->next_link->data);

    // Accessing data of ob1, ob2 and ob3 by ob2
    printf("%d\t", ob2.prev_link->data);
    printf("%d\t", ob2.data);
    printf("%d\n", ob2.next_link->data);

    // Accessing data of ob1, ob2 and ob3 by ob3
    printf("%d\t", ob3.prev_link->prev_link->data);
    printf("%d\t", ob3.prev_link->data);
    printf("%d", ob3.data);
    return 0;
}
Java
public class Main {
    public static void main(String[] args)
    {
        // Create nodes
        Node ob1 = new Node(); // Node1
        Node ob2 = new Node(); // Node2
        Node ob3 = new Node(); // Node3

        // Initialize data for each node
        ob1.data = 10;
        ob2.data = 20;
        ob3.data = 30;

        // Set forward links
        ob1.next_link = ob2;
        ob2.next_link = ob3;

        // Set backward links
        ob2.prev_link = ob1;
        ob3.prev_link = ob2;

        // Accessing data of ob1, ob2 and ob3 by ob1
        System.out.println(ob1.data + "\t"
                           + ob1.next_link.data + "\t"
                           + ob1.next_link.next_link.data);

        // Accessing data of ob1, ob2 and ob3 by ob2
        System.out.println(ob2.prev_link.data + "\t"
                           + ob2.data + "\t"
                           + ob2.next_link.data);

        // Accessing data of ob1, ob2 and ob3 by ob3
        System.out.println(ob3.prev_link.prev_link.data
                           + "\t" + ob3.prev_link.data
                           + "\t" + ob3.data);
    }
}

class Node {
    int data;
    Node prev_link;
    Node next_link;
}
Python
class node:
    def __init__(self):
        self.data = 0
        self.prev_link = None
        self.next_link = None


if __name__ == '__main__':
    ob1 = node()  # Node1

    # Initialization
    ob1.prev_link = None
    ob1.next_link = None
    ob1.data = 10

    ob2 = node()  # Node2

    # Initialization
    ob2.prev_link = None
    ob2.next_link = None
    ob2.data = 20

    ob3 = node()  # Node3

    # Initialization
    ob3.prev_link = None
    ob3.next_link = None
    ob3.data = 30

    # Forward links
    ob1.next_link = ob2
    ob2.next_link = ob3

    # Backward links
    ob2.prev_link = ob1
    ob3.prev_link = ob2

    # Accessing  data of ob1, ob2 and ob3 by ob1
    print(ob1.data, end='\t')
    print(ob1.next_link.data, end='\t')
    print(ob1.next_link.next_link.data)

    # Accessing data of ob1, ob2 and ob3 by ob2
    print(ob2.prev_link.data, end='\t')
    print(ob2.data, end='\t')
    print(ob2.next_link.data)

    # Accessing data of ob1, ob2 and ob3 by ob3
    print(ob3.prev_link.prev_link.data, end='\t')
    print(ob3.prev_link.data, end='\t')
    print(ob3.data)
JavaScript
class Node {
    constructor(data) {
        this.data = data;
        this.prev_link = null;
        this.next_link = null;
    }
}

function main() {
    // Create nodes
    let ob1 = new Node(); // Node1
    let ob2 = new Node(); // Node2
    let ob3 = new Node(); // Node3

    // Initialize data for each node
    ob1.data = 10;
    ob2.data = 20;
    ob3.data = 30;

    // Set forward links
    ob1.next_link = ob2;
    ob2.next_link = ob3;

    // Set backward links
    ob2.prev_link = ob1;
    ob3.prev_link = ob2;

    // Accessing data of ob1, ob2, and ob3 by ob1
    console.log(ob1.data + "\t" + ob1.next_link.data + "\t" + ob1.next_link.next_link.data);

    // Accessing data of ob1, ob2, and ob3 by ob2
    console.log(ob2.prev_link.data + "\t" + ob2.data + "\t" + ob2.next_link.data);

    // Accessing data of ob1, ob2, and ob3 by ob3
    console.log(ob3.prev_link.prev_link.data + "\t" + ob3.prev_link.data + "\t" + ob3.data);
}

// Execute the main function
main();

Output
10    20    30
10    20    30
10    20    30

In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential structure ‘node’. And they are connected using their links in such a way that any of them can easily access each other’s data. This is the beauty of the self referential structures. The connections can be manipulated according to the requirements of the programmer.

Applications: Self-referential structures are very useful in creation of other complex data structures like: 



Previous Article
Next Article

Similar Reads

Inversion count in Array Using Self-Balancing BST
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If an array is already sorted then the inversion count is 0. If an array is sorted in the reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j. For simplicity, we may assume that all e
15+ min read
Self Descriptive Number
Given an integer N, the task is to find all the self-descriptive numbers from 1 to N A self-descriptive number is an integer n in given base b is b digits long in which each digit at position p (the most significant digit being at position 0 and the least significant at position b - 1) counts how many times a digit p is in n. For example in base 10
11 min read
Self-Balancing Binary Search Trees
Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average. Examples: The most common examples of self-balan
4 min read
Find the centroid of a non-self-intersecting closed Polygon
Given N vertices of the polygon, the task is to find the centroid of the polygonExamples: Input: ar = {{0, 0}, {0, 8}, {8, 8}, {8, 0}} Output: {Cx, Cy} = {4, 4} Input: ar = {{1, 2}, {3, -4}, {6, -7}} Output: {Cx, Cy} = {3.33, -3} Approach: The centroid of a non-self-intersecting closed polygon defined by n vertices (x0, y0), (x1, y1), ..., (xn-1, y
5 min read
Why You Should Become a Self-Taught Programmer?
You may have heard about Jack Dorsey (Twitter), Mark Zuckerberg (Facebook), Kevin Systrom (Instagram) and many others. Right, these are one of the top programmers and tech enthusiasts who are currently ruling the world. But, have you ever thought that what made them so accomplished and proficient in the world of programming? No, it is not any colle
8 min read
Self Numbers
A Number N is said to be Self Number if it can not be written as M + sum of digits of M for any M.The first few Self numbers are: 1, 3, 5, 7, 9, 20, 31, 42................ Check if N is a Self number Given an integer N, the task is to find if this number is Self number or not. Examples: Input: N = 3 Output: Yes Explanation: 1 + sumofDigits(1) = 2 2
5 min read
Self Balancing BST in JavaScript
A self-balancing binary search tree (BST) is a type of binary search tree that automatically keeps its height balanced in order to guarantee that operations such as searching, inserting, and deleting elements in the tree take less time on average. How do self-balancing BSTs maintain height balance? Self-balancing binary search trees (BSTs) maintain
11 min read
Find the Kth smallest term in self cross-product Array
Given an array arr[] of n elements, find the Kth lexicographically smallest in its corresponding cross-product array. For an array arr of n elements, the cross product of the array, cp_arr, is defined as cp_arr = {{arr[i], arr[j}} for all 0 < i, j < n. Examples: Input: n = 3, K = 7, arr[] = {3, 1, 2} Output: [3, 1]Explanation: [3, 1, 2] * [3,
8 min read
Self Organizing List : Move to Front Method
Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times.  So, a s
10 min read
Self Organizing List : Count Method
Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times.  So, a s
11 min read
Self Organizing List | Set 1 (Introduction)
The worst case search time for a sorted linked list is O(n). With a Balanced Binary Search Tree, we can skip almost half of the nodes after one comparison with root. For a sorted array, we have random access and we can apply Binary Search on arrays. One idea to make search faster for Linked Lists is Skip List. Another idea (which is discussed in th
3 min read
Best Way To Start With Competitive Programming - GeeksforGeeks CP Self-Placed Course
Remember the day of your childhood memories when the first time your parents and friends handover some jigsaw puzzle games to you and you accepted the challenge to solve it (We know we just have brought a smile on your face...). It was interesting and fun for you to solve your first puzzle and then the next one, then the next one, and so on... Thro
6 min read
DSA Self Paced Course – Basic to Advanced Online Course By GeeksforGeeks
If you're preparing for a tech interview with a product-based company or planning to do the same? Are you looking for a DSA Course? Don't know how to begin with data structures and algorithms? Then you are at the right place. Almost every IT giant including Facebook, Google, Amazon, etc. focuses more on the DSA skills of the candidates during the i
6 min read
Product of Array Except Self
Given an array arr[] of n integers, construct a Product Array prod[] (of the same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Example : Input: arr[] = {10, 3, 5, 6, 2}Output: prod[] = {180, 600, 360, 300, 900}Explanation :Product of all except 10 = 3 * 5 * 6 * 2 = 180Product of all except 3 = 10 * 5 *
15+ min read
Data Structures | Linked List | Question 1
What does the following function do for a given Linked List with first node as head? void fun1(struct node* head) { if(head == NULL) return; fun1(head->next); printf(\"%d \", head->data); } (A) Prints all nodes of linked lists (B) Prints all nodes of linked list in reverse order (C) Prints alternate nodes of Linked List (D) Prints alternate n
2 min read
Data Structures | Stack | Question 1
Following is C like pseudo code of a function that takes a number as an argument, and uses a stack S to do processing. void fun(int n) { Stack S; // Say it creates an empty stack S while (n > 0) { // This line pushes the value of n%2 to stack S push(&S, n%2); n = n/2; } // Run while Stack S is not empty while (!isEmpty(&S)) printf("
1 min read
Data Structures | Queue | Question 1
Following is C like pseudo-code of a function that takes a Queue as an argument, and uses a stack S to do processing. C/C++ Code void fun(Queue *Q) { Stack S; // Say it creates an empty stack S // Run while Q is not empty while (!isEmpty(Q)) { // deQueue an item from Q and push the dequeued item to S push(&S;, deQueue(Q)); } // Run while Stack S is
1 min read
Data Structures | Stack | Question 2
Which one of the following is an application of Stack Data Structure? (A) Managing function calls (B) The stock span problem (C) Arithmetic expression evaluation (D) All of the above Answer: (D) Explanation: See http://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Applications
1 min read
Data Structures | Linked List | Question 2
Which of the following points is/are true about Linked List data structure when it is compared with array? (A) Arrays have better cache locality that can make them better in terms of performance. (B) It is easy to insert and delete elements in Linked List (C) Random access is not allowed in a typical implementation of Linked Lists (D) The size of a
2 min read
Data Structures | Linked List | Question 3
Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as prev and next pointer as next. C/C++ Code void fun(struct node **head_ref) { struct node *temp = NULL; struct node *current = *head_ref; while (current != NULL) { temp = current->prev; c
2 min read
Data Structures | Queue | Question 2
Which one of the following is an application of Queue Data Structure? (A) When a resource is shared among multiple consumers. (B) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes (C) Load Balancing (D) All of the above Answer: (D) Explanation: (A) When a resource is shared among mult
2 min read
Data Structures | Binary Trees | Question 1
Which of the following is true about Binary Trees? (A) Every binary tree is either complete or full. (B) Every complete binary tree is also a full binary tree. (C) Every full binary tree is also a complete binary tree. (D) No binary tree is both complete and full. (E) None of the above Answer: (E)Explanation: A full binary tree (sometimes proper bi
2 min read
Data Structures | Tree Traversals | Question 1
Following function is supposed to calculate the maximum depth or height of a Binary tree -- the number of nodes along the longest path from the root node down to the farthest leaf node. int maxDepth(struct node* node) { if (node==NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDep
1 min read
Data Structures | Binary Trees | Question 15
If arity of operators is fixed, then which of the following notations can be used to parse expressions without parentheses? a) Infix Notation (Inorder traversal of a expression tree) b) Postfix Notation (Postorder traversal of a expression tree) c) Prefix Notation (Preorder traversal of a expression tree) (A) b and c (B) Only b (C) a, b and c (D) N
1 min read
Data Structures | Tree Traversals | Question 2
What is common in three different types of traversals (Inorder, Preorder and Postorder)? (A) Root is visited before right subtree (B) Left subtree is always visited before right subtree (C) Root is visited after left subtree (D) All of the above (E) None of the above Answer: (B) Explanation: The order of inorder traversal is LEFT ROOT RIGHT The ord
1 min read
Data Structures | Tree Traversals | Question 3
The inorder and preorder traversal of a binary tree are d b e a f c g and a b d e c f g, respectively. The postorder traversal of the binary tree is: (A) d e b f g c a (B) e d b g f c a (C) e d b f g c a (D) d e f g b c a Answer: (A) Explanation: Below is the given tree. a / \ / \ b c / \ / \ / \ / \ d e f g Quiz of this Question
1 min read
Data Structures | Binary Trees | Question 3
What are the main applications of tree data structure? Manipulate hierarchical data Make information easy to search Manipulate sorted lists of data Router algorithms Form of a multi-stage decision-making, like Chess Game. As a workflow for compositing digital images for visual effects (A) 1, 2, 3, 4 and 6 (B) 1, 2, 3, 4 and 5 (C) 1, 3, 4, 5 and 6 (
1 min read
Data Structures | Binary Trees | Question 4
Level of a node is distance from root to that node. For example, level of root is 1 and levels of left and right children of root is 2. The maximum number of nodes on level i of a binary tree is In the following answers, the operator '^' indicates power. (A) 2^(i-1) (B) 2^i (C) 2^(i+1) (D) 2^[(i+1)/2] Answer: (A) Explanation: Number of nodes of bin
1 min read
Data Structures | Binary Trees | Question 15
In a complete k-ary tree, every internal node has exactly k children or no child. The number of leaves in such a tree with n internal nodes is: (A) nk (B) (n – 1) k+ 1 (C) n( k – 1) + 1 (D) n(k – 1) Answer: (C) Explanation: For an k-ary tree where each node has k children or no children, following relation holds L = (k-1)*n + 1 Where L is the numbe
1 min read
Data Structures | Tree Traversals | Question 4
What does the following function do for a given binary tree? int fun(struct node *root) { if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; return 1 + fun(root->left) + fun(root->right); } (A) Counts leaf nodes (B) Counts internal nodes (C) Returns height where height is defined as number of ed
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg