Insertion in singly linked list at beginning
Inserting a new element into a singly linked list at beginning is quite simple. We just need to make a few adjustments in the node links. There are the following steps which need to be followed in order to inser a new node in the list at beginning.
- Allocate the space for the new node and store data into the data part of the node. This will be done by the following statements.
- Make the link part of the new node pointing to the existing first node of the list. This will be done by using the following statement.
- At the last, we need to make the new node as the first node of the list this will be done by using the following statement.
Linked List Operations: Traverse, Insert and Delete
In this tutorial, you will learn different operations on a linked list. Also, you will find implementation of linked list operations in C/C++, Python and Java.
There are various linked list operations that allow us to perform different actions on linked lists. For example, the insertion operation adds a new element to the linked list.
Here's a list of basic linked list operations that we will cover in this article.
- Traversal - access each element of the linked list
- Insertion - adds a new element to the linked list
- Deletion - removes the existing elements
- Search - find a node in the linked list
- Sort - sort the nodes of the linked list
Before you learn about linked list operations in detail, make sure to know about Linked List first.
Things to Remember about Linked List
- head points to the first node of the linked list
- next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list.
In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:
struct node {
int data;
struct node *next;
};
Data Structure and Algorithms - Linked List
Advertisements
Previous Page
Next Page
A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array. Following are the important terms to understand the concept of Linked List.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
LinkedList − A Linked List contains the connection link to the first link called First.
Linked List Data Structure
- Last Updated :
01 Feb, 2022
Practice Problems on Linked List
Recent Articles on Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:
In simple words, a linked list consists of nodes where each node contains a data field and a reference(link) to the next node in the list.
Topics :
- Singly Linked List
- Circular Linked List
- Doubly Linked List
Singly Linked List :
- Introduction to Linked List
- Linked List vs Array
- Linked List Insertion
- Linked List Deletion (Deleting a given key)
- Linked List Deletion (Deleting a key at given position)
- Write a function to delete a Linked List
- Find Length of a Linked List (Iterative and Recursive)
- Search an element in a Linked List (Iterative and Recursive)
- Write a function to get Nth node in a Linked List
- Nth node from the end of a Linked List
- Print the middle of a given linked list
- Write a function that counts the number of times a given int occurs in a Linked List
- Detect loop in a linked list
- Find length of loop in linked list
- Function to check if a singly linked list is palindrome
- Remove duplicates from a sorted linked list
- Remove duplicates from an unsorted linked list
- Swap nodes in a linked list without swapping data
- Pairwise swap elements of a given linked list
- Move last element to front of a given Linked List
- Intersection of two Sorted Linked Lists
- Intersection point of two Linked Lists.
- QuickSort on Singly Linked List
- Segregate even and odd nodes in a Linked List
- Reverse a linked list
More >>
Circular Linked List :
- Circular Linked List Introduction and Applications,
- Circular Linked List Traversal
- Split a Circular Linked List into two halves
- Sorted insert for circular linked list
- Check if a linked list is Circular Linked List
- Convert a Binary Tree to a Circular Doubly Link List
- Circular Singly Linked List | Insertion
- Deletion from a Circular Linked List
- Circular Queue | Set 2 (Circular Linked List Implementation)
- Count nodes in Circular linked list
- Josephus Circle using circular linked list
- Convert singly linked list into circular linked list
- Circular Linked List | Set 1 (Introduction and Applications)
- Circular Linked List | Set 2 (Traversal)
- Implementation of Deque using circular array
- Exchange first and last nodes in Circular Linked List
More >>
Doubly Linked List :
- Doubly Linked List Introduction and Insertion
- Delete a node in a Doubly Linked List
- Reverse a Doubly Linked List
- The Great Tree-List Recursion Problem.
- Copy a linked list with next and arbit pointer
- QuickSort on Doubly Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Merge Sort for Doubly Linked List
- Create a Doubly Linked List from a Ternary Tree
- Find pairs with given sum in doubly linked list
- Insert value in sorted way in a sorted doubly linked list
- Delete a Doubly Linked List node at a given position
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Remove duplicates from a sorted doubly linked list
- Delete all occurrences of a given key in a doubly linked list
- Remove duplicates from an unsorted doubly linked list
- Sort the biotonic doubly linked list
- Sort a k sorted doubly linked list
- Convert a given Binary Tree to Doubly Linked List | Set
- Program to find size of Doubly Linked List
- Sorted insert in a doubly linked list with head and tail pointers
- Large number arithmetic using doubly linked list
- Rotate Doubly linked list by N nodes
- Priority Queue using doubly linked list
- Reverse a doubly linked list in groups of given size
- Doubly Circular Linked List | Set 1 (Introduction and Insertion)
- Doubly Circular Linked List | Set 2 (Deletion)
More >>
Misc :
- Skip List | Set 1 (Introduction)
- Skip List | Set 2 (Insertion)
- Skip List | Set 3 (Searching and Deletion)
- Reverse a stack without using extra space in O(n)
- An interesting method to print reverse of a linked list
- Linked List representation of Disjoint Set Data Structures
- Sublist Search (Search a linked list in another list)
- How to insert elements in C++ STL List ?
- Unrolled Linked List | Set 1 (Introduction)
- A Programmer’s approach of looking at Array vs. Linked List
- How to write C functions that modify head pointer of a Linked List?
- Given a linked list which is sorted, how will you insert in sorted way
- Can we reverse a linked list in less than O(n)?
- Practice questions for Linked List and Recursion
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Squareroot(n)-th node in a Linked List
- Find the fractional (or n/k – th) node in linked list
- Find modular node in a linked list
- Construct a linked list from 2D matrix
- Find smallest and largest elements in singly linked list
- Arrange consonants and vowels nodes in a linked list
- Partitioning a linked list around a given value and If we don’t care about making the elements of the list “stable”
- Modify contents of Linked List
Quick Links :
- ‘Practice Problems’ on Linked List
- ‘Videos’ on Linked List
- ‘Quizzes’ on Linked List
If you still need more assistance with your placement preparation, have a look at our Complete Interview Preparation Course. The course has been designed by our expert mentors to help students crack the coding interview of top product or service-based organizations . You get access to premium lectures, 200+ coding questions bank, resume building tips, and lifetime access to the course content. So to make sure that your next programming interview doesn’t feel like an interrogation, enroll in Complete Interview Preparation and give a boost to your placement preparation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Linked List | Set 2 (Inserting a node)
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.
All programs discussed in this post consider the following representations of linked list.
C++
// A linked list node
class Node
{
public:
int data;
Node *next;
};
// This code is contributed by rathbhupendra
|
C
// A linked list node
struct Node
{
int data;
struct Node *next;
};
|
Java
// Linked List Class
class LinkedList
{
Node head; // head of list
/* Node Class */
class Node
{
int data;
Node next;
// Constructor to create a new node
Node(int d) {data = d; next = null; }
}
}
|
Python
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None
|
C#
/* Linked list Node*/
public class Node
{
public int data;
public Node next;
public Node(int d) {data = d; next = null; }
}
|
Javascript
// Linked List Class
var head; // head of list
/* Node Class */
class Node {
// Constructor to create a new node
constructor(d) {
this.data = d;
this.next = null;
}
}
// This code is contributed by todaysgaurav
|
In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways
1) At the front of the linked list
2) After a given node.
3) At the end of the linked list.
Traverse a Linked List
Accessing the nodes of a linked list in order to process it is called traversing a linked list. Normally we use the traverse operation to display the contents or to search for an element in the linked list. The algorithm for traversing a linked list is given below.
Algorithm: Traverse
Step 1: [INITIALIZE] SET PTR = HEAD
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Apply process to PTR -> DATA
Step 4: SET PTR = PTR->NEXT
[END OF LOOP]
Step 5: EXIT
- We first initialize PTR with the address of HEAD. Now the PTR points to the first node of the linked list.
- A while loop is executed, and the operation is continued until PTR reaches the last node (PTR = NULL).
- Apply the process(display) to the current node.
- Move to the next node by making the value of PTR to the address of next node.
The following block of code prints all elements in a linked list in C.
struct node *ptr = head;
printf("Elements in the linked list are : ");
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
Inserting Elements to a Linked List
We will see how a new node can be added to an existing linked list in the following cases.
- The new node is inserted at the beginning.
- The new node is inserted at the end.
- The new node is inserted after a given node.
Insert a Node at the beginning of a Linked list
Consider the linked list shown in the figure. Suppose we want to create a new node with data 24 and add it as the first node of the list. The linked list will be modified as follows.
- Allocate memory for new node and initialize its DATA part to 24.
- Add the new node as the first node of the list by pointing the NEXT part of the new node to HEAD.
- Make HEAD to point to the first node of the list.
Algorithm: InsertAtBeginning
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = HEAD
Step 6: SET HEAD = NEW_NODE
Step 7: EXIT
Note that the first step of the algorithm checks if there is enough memory available to create a new node. The second, and third steps allocate memory for the new node.
This algorithm can be implemented in C as follows:
struct node *new_node;
new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = 24;
new_node->next = head;
head = new_node;
Insert a Node at the end of a Linked list
Take a look at the linked list in the figure. Suppose we want to add a new node with data 24 as the last node of the list. Then the linked list will be modified as follows.
- Allocate memory for new node and initialize its DATA part to 24.
- Traverse to last node.
- Point the NEXT part of the last node to the newly created node.
- Make the value of next part of last node to NULL.
Algorithm: InsertAtEnd
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 10
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = NULL
Step 6: SET PTR = HEAD
Step 7: Repeat Step 8 while PTR -> NEXT != NULL
Step 8: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 9: SET PTR -> NEXT = NEW_NODE
Step 10: EXIT
This can be implemented in C as follows,
struct node *new_node;
new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = 24;
new_node->next = NULL;
struct node *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new_node;
Insert a Node after a given Node in a Linked list
The last case is when we want to add a new node after a given node. Suppose we want to add a new node with value 24 after the node having data 9. These changes will be done in the linked list.
- Allocate memory for new node and initialize its DATA part to 24.
- Traverse the list until the specified node is reached.
- Change NEXT pointers accordingly.
Algorithm: InsertAfterAnElement
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET PTR = HEAD
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while PREPTR -> DATA != NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 1 : PREPTR -> NEXT = NEW_NODE
Step 11: SET NEW_NODE -> NEXT = PTR
Step 12: EXIT
Inserting a node at the beginning of a linked list
The new node will be added at the beginning of a linked list.
Example
Assume that the linked list has elements: 20 30 40 NULL
If we insert 100, it will be added at the beginning of a linked list.
After insertion, the new linked list will be
100 20 30 40 NULL