Jerome Papalie
Jerome Papalie

Reputation: 21

Linked List Definition

This snippet of code is from an assignment I'm working on at school for a data structures module. This bit of code is provided in the question, and I can't understand this.

typedef struct _listnode {
    int item;
    struct _listnode *next;
} ListNode; // You should not change the definition of ListNode

typedef struct _linkedlist {
    int size;
    ListNode *head;
} LinkedList; // You should not change the definition of LinkedList 

I am confused because my lecture slides and sites I've been to check this out have just defined the node, and not the second one.

Can anyone help me with this please?

Upvotes: 1

Views: 311

Answers (2)

vcode
vcode

Reputation: 21

A linked list is held using a local pointer variable which points to the first item of the list. If that pointer is also NULL, then the list is considered to be empty.

include <stdio.h>

int main() {
    typedef struct node {
        int val;
        struct node * next;
    } node_t;


return 0;
}

Upvotes: 0

fluter
fluter

Reputation: 13786

LinkedList is a struct denoting a linked list by holding its head and its size, while each node in the list is denoted by struct ListNode. This is a common paradigm if you want to maintain the size of the linked list, in the case you can easily get the number of nodes in the list without have to iterate through it. On the other hand, if size is not concern, you can just use a pointer to node for the head without have to define the LinkedList struct.

So for an empty list, you would have:

LinkedList list = (struct LinkedList){0, NULL};

For a list with one node:

ListNode node;
node.item = 0;
node.next = NULL;
list.head = &node;
list.size = 1;

Upvotes: 1

Related Questions