Linked Lists Questions

Saandeep Sreerambatla

Saandeep Sreerambatla

@saandeep-sreerambatla-hWHU1M Oct 9, 2024
This is the basic declaration we do while working on linked lists.

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

why is the next declared as a pointer? and not as a just

struct node next; ??


I will start with basic and then go for advanced questions.

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • aarthivg

    aarthivg

    @aarthivg-HH344f Mar 14, 2012

    English-Scared
    This is the basic declaration we do while working on linked lists.

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

    why is the next declared as a pointer? and not as a just

    struct node next; ??


    I will start with basic and then go for advanced questions.
    linked list consist of two parts data and reference to the next node
  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Mar 14, 2012

    True, but the reference can also be accessed by normal variables using logic!

    and think in this perspective, is it valid if I declare

    struct node {
    int data;
    struct node next;
    };

    If valid why dont we use, If invalid why is it invalid?
  • aarthivg

    aarthivg

    @aarthivg-HH344f Mar 14, 2012

    The field of each node that contains the address of the next node is usually called the next link or next pointer.

    So reference cant be used as a normal variable.
  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Mar 14, 2012

    OK the answer I was expecting is,

    if we donot use a pointer, and declare a variable of struct node inside struct node, then compiler donot know how much memory to allocate to that variable as the parent structure declaration is not complete yet.

    if we use a pointer, then compiler knows that , its a pointer and it stores address of something . so it allocates memory.
  • greatcoder

    greatcoder

    @greatcoder-Zo4hpf Mar 15, 2012

    Here Because next is not a structure itself , it is a pointer to the next node in the linked list.
  • Saandeep Sreerambatla

    Saandeep Sreerambatla

    @saandeep-sreerambatla-hWHU1M Mar 17, 2012

    #-Link-Snipped-# Coder : Please elaborate!!