Javatpoint Logo
Javatpoint Logo

Add Node to Linked List in C

A linked list is a data structure used in computer programming that consists of a sequence of elements, each containing a reference (link) to the next element. Unlike an array, the elements in a linked list are not stored in contiguous memory locations. Instead, each element is stored in a separate memory location and linked to the next element via a reference.

Linked lists are useful for creating dynamic data structures and can be easily inserted, deleted or updated. They are commonly used in programming languages such as C and C++, and can also be found in other languages such as Java and Python. However, linked lists have a slower access time than arrays, since elements in a linked list must be accessed by traversing the list, starting from the first element.

C Code Implementation:

A linked list in C can be implemented using a class or struct, which defines the properties and methods of the linked list. The class or struct should contain a pointer to the first element of the list, called the head, and a variable to store the number of elements in the list. Here is an example of a large linked list implementation in C


15 10 5 
15 5 
Number of elements: 2

Add Node to Linked List in C

Here is an example of a simple code in C that demonstrates how to add a new node to a linked list with a main function:

C Code


5 10 15


In this code, the function addNode takes two arguments, a pointer to a linked list and an integer value, which will be stored in the data field of the new node. First, it creates a new node object, assigns the value to the data field and sets the next field to NULL.

Linked lists are better for dynamic data structures and inserting, deleting elements, while arrays are better for quick random access and have better cache locality. However, it depends on the use case and the particular implementation.

Then it checks if the head of the list is NULL, if so, it assigns the new node to the head, otherwise it iterates through the list to find the last node and add new node to the end of the list. In the main function, it creates an object of LinkedList, and set head to NULL, call the addNode function multiple times to add some values, then iterates through the list to print all values.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA