Home > OS >  How to initialize this NodeList class in C
How to initialize this NodeList class in C

Time:02-28

I'm pretty newbie in C language and I have this little code in which I want to do some test in the main code.

struct ListNode
{
    int val;
    struct ListNode *next;
};

I want to create some examples (For example: 4 -> 9 -> 1) in the main code, but I don't really know how to initialize them. Thank you in advance.

CodePudding user response:

I would do something like this:

struct ListNode* addnode(struct ListNode *head,int val)
{
    struct ListNode* newnode = malloc(sizeof(*this));
    newnode->val = val;
    newnode->next = NULL;
    if (!head) head = newnode;
    else {
        struct ListNode *this = head;
        while(this->next)
            this = this->next;
        this->next = newnode;
    }
    return head;
}

int main(void)
{
    struct ListNode *head = NULL;

    head = addnode(head,4);
    addnode(head,9);
    addnode(head,1);

    return 0;
}

CodePudding user response:

Using this structure you need in main at first to declare a pointer to the head node of the list and initialize it as a null pointer. For example

struct ListNode *head = NULL;

Then you need to write a function that will store values in the list by dynamically allocating nodes that will be added to the list. Or you could create dynamically nodes in a loop if you a going to do all the functionality in main.

Pay attention to that if you have a singly-linked list then it is more efficient to add new nodes to the beginning of the list. Or if you want to add new nodes to the tail of the list then you should declare a two-sided singly-linked list like for example

struct ListNode
{
    int val;
    struct ListNode *next;
};

struct List
{
    struct ListNode *head;
    struct ListNode *tail;
};

In this case declaration of the list in main can look like

struct List list = { .head = NULL, .tail = NULL };
  • Related