0% found this document useful (0 votes)
1 views

Algorithm to insert a node at front

The document outlines the steps to insert a new element at the beginning of a singly linked list, which involves allocating space for the new node, linking it to the existing first node, and updating the head pointer. It also provides an algorithm for inserting a new node at the end of the list. The time complexity for inserting a node at the beginning is O(1).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Algorithm to insert a node at front

The document outlines the steps to insert a new element at the beginning of a singly linked list, which involves allocating space for the new node, linking it to the existing first node, and updating the head pointer. It also provides an algorithm for inserting a new node at the end of the list. The time complexity for inserting a node at the beginning is O(1).
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Insertion in the singly linked list at the beginning

Inserting a new element into a singly linked list at the beginning is quite simple. We just need
to make a few adjustments in the node links. There are the following steps that need to be
followed in order to insert a new node in the list at the beginning.

1. Allocate the space for the new node and store data into the data part of the node and store
NULL at the address part of the node.

ptr = (struct node *) malloc(sizeof(struct node *));

ptr → data = item

ptr->next=NULL

2. Make the linked part of the new node point to the existing first node of the list.

ptr->next = head;
3. At the last, we need to make the new node the first node of the list.

head = ptr;

Algorithm to insert a new node at the end

Step 1: IF HEAD = NULL


Write OVERFLOW
Go to Step 6
[END OF IF]
Step 2: SET PTR as a new node
Step 3: SET PTR → DATA = VAL
Step 4: SET PTR → NEXT = HEAD
Step 5: SET HEAD= PTR
Step 6: EXIT

The time complexity to insert a node at the beginning of the given linked list is: O(1)

You might also like