Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Insert node at end of linked list

Suppose following data are inserting in linked list.

Input :201 202 203 204 205 206 207 208

Algorithm:

Step 1: Create memory block using malloc function. If malloc function are create memory then it will return address of this memory block. Otherwise memory overflow problem.

Step 2: Created memory block assign data value and next pointer value.

Step 3: Find last node and attach this newly created memory to end position. if linked list are empty then assign this address of root pointer of given linked list.

Finding last node this process are tacking O(n) time.

Insertion process:

Insert first element 201 of linked list. note that initial linked list are empty. created memory block and assign data value 201 and next pointer value is NULL. Assign this first node address of root pointer.

root_ptr201

Insert second element 202 of linked list. similar way create memory block and assign data value and pointer value. In this case we need to find the last node of linked list. find last node and attach this new node.

root_ptr201202

Similar way to inserting other node 203,204,205,206,207. after insert linked list is.

root_ptr207206205204203202201

Insert last node 208.

root_ptr208207206205204203202201

View insertion at beginning.

Try it yourself

Code execution:

Stack Areamainroot(pointer)insert_datanew_node(pointer)root(pointer)temp(pointer)value (int) =208 Heap Areastruct Nodedata (int)= 201next (pointer) struct Nodedata (int)= 202next (pointer) struct Nodedata (int)= 203next (pointer) struct Nodedata (int)= 204next (pointer) struct Nodedata (int)= 205next (pointer) struct Nodedata (int)= 206next (pointer) struct Nodedata (int)= 207next (pointer) struct Nodedata (int)= 208next (pointer)= NULL

Note that not given all step of execution process here.View How to insert linked list element and so on.

Try it yourself

C program to insert node at end of given linked list.

OutPut:

Spread the post

Recommended Posts: