Linked list insertion
In this article, we will learn how to insert a node into a linked list. We can see that 4 different cases occur.
- We want to insert a node before the head of the linked list. This operation is similar to the push operation in a stack.
- We want to insert a node at the end of the linked list (that is, next to the tail node).
- We want to insert a node at the ith position of the linked list.
- We have a reference to the node, and then we want to insert the new node.
Linked list insertion algorithm
Let head
be a pointer to the first node of the linked list, and let x
be the data to be inserted into the linked list.
push()
Insert a node
at the beginning of a linked list
x
Create a new node with datatemp
.-
Set
temp->next
to to inserthead
before .head
temp
-
Sets
temp
to the beginning of the linked list.
append()
Insert a node at the end of
the linked list
x
Create a new node with datatemp
.-
Initializes pointer
head
totail
. -
If the linked list is empty,
temp
sets to the linked list'shead
and then returns . -
Otherwise, iterate to the end of the linked list, making
tail->next
!=NULL
so that you reach the last element -
Set
tail->next
totemp
.
Insert a node at position insertNpos()
in
the linked listi-th
-
If position
pos
<=0
, then return; otherwise return 0. -
If
pos
==0
andhead
is empty, create ax
new node with data and set it tohead
. -
If
pos
==1
, then callpush()
. -
Additionally,
x
create a new node with the datatemp
. -
Initializes pointer
head
tocurr
. -
When
pos--
, do the following.-
If
pos
==1
,-
If
curr
notNULL
-
Set
temp->next
tocurr->next
tocurr
insert aftertemp
. -
Set
curr->next
totemp
tocurr
connect totemp
.
-
Set
- return;
-
If
-
Otherwise
curr
set tocurr->next
.
-
Inserts a node next to the given node's reference −insertAfter()
-
If
prev
==NULL
, then return; x
Create a new node with datacurr
.curr->next
Point toprev->next
to add a new node after prev.prev->next
Point tocurr
to complete the insertion.
Linked list insertion diagram
Suppose we have a node temp
with data value equal to 5
, and we want to insert it into the linked list. Let's consider all 4
the cases and illustrate how the above algorithm works.
To insert a node at the beginning of a linked list −push()
temp
Set the pointer of tohead
.head
Point totemp
.
append()
Insert a node at the end of
the linked list
-
Point
curr
tohead
, the data is2
. -
Set
curr
tocurr->next
, and move it to3
the node with data . -
Set
curr
tocurr->next
, and move it to4
the node with data . -
Exit the while loop and
curr->next
settemp
i-th
Insert a node at position
in the linked list -insertNpos()
We insert the node at position 3
.
-
Set
curr
to point tohead
and data to be1
,pos
=pos-1
=2
. -
Set
curr
tocurr->next
, and move it to the node whose data is3
,pos
=pos -1
=1
. -
Set
temp->next
tocurr->next
so thatcurr
temp is inserted after . -
Set
curr->next
totemp
to complete the insertion of betweencurr
and .curr->next
temp
insertAfter()
Inserts a node next to
the given node 's reference
-
Set
temp->next
to to insertprev->next
betweenprev
and .prev->next
temp
-
Set
prev->next
totemp
to complete the insert.
Linked list insertion implementation
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
this->data = x;
this->next = NULL;
}
};
void push(Node** head, int x)
{
Node* temp = new Node(x);
temp->next = (*head);
(*head) = temp;
}
void insertAfter(Node* prev, int x)
{
if (prev == NULL) {
return;
}
Node* curr = new Node(x);
curr->next = prev->next;
prev->next = curr;
}
void printList(Node* head)
{
Node*curr = head;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
}
void insertNpos(Node**head, int x, int pos) {
if (pos <= 0) {
return;
}
if (!head && pos == 1) {
*head = new Node(x);
}
else if (pos == 1) {
push(head, x);
}
Node* temp = new Node(x);
Node*curr = *head;
while (pos--) {
if (pos == 1) {
if (curr) {
temp->next = curr->next;
curr->next = temp;
}
return;
}
curr = curr->next;
}
}
void append(Node** head, int x)
{
Node* temp = new Node(x);
Node *tail = *head;
if (*head == NULL)
{
*head = temp;
return;
}
while (tail->next != NULL)
tail = tail->next;
tail->next = temp;
return;
}
int main()
{
Node* head = new Node(1);
head -> next = new Node(2);
printList(head); cout << "\n";
push(&head, 3);
push(&head, 4);
printList(head); cout << "\n";
append(&head, 5);
printList(head); cout << "\n";
insertAfter(head->next->next, 6);
printList(head); cout << "\n";
insertNpos(&head, 24, 2);
printList(head);
return 0;
}
Complexity of linked list insertion algorithm
Time Complexity
- Average situation
To insert a node into the position in the linked list 第 i 个
, we have to visit i
nodes. So, the time complexity is about O(i)
. And we have nodes in the linked list n
, so the time complexity in the average case is O(n/2)
or O(n)
. The time complexity is about O(n)
.
- Best Case
The best case scenario is when we want to insert a node at the beginning of the linked list or when there is a reference to the node before the insertion site. The time complexity for the best case scenario is O(1)
.
- Worst case scenario
The worst case time complexity is O(n)
. This is the same as the average case time complexity.
Space complexity
The space complexity of this insertion algorithm is O(1)
, since curr
no additional space is required except for the pointer.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Learning the Sorting Algorithm - Insertion Sort (Concepts)
Publish Date:2025/03/19 Views:96 Category:ALGORITHM
-
What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a
Learning path of sorting algorithm - direct insertion sort
Publish Date:2025/03/19 Views:176 Category:ALGORITHM
-
This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide
Learning the sorting algorithm - Binary Insertion Sort
Publish Date:2025/03/19 Views:143 Category:ALGORITHM
-
This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s
The road to learning sorting algorithms - table insertion sort
Publish Date:2025/03/19 Views:194 Category:ALGORITHM
-
Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original
The road to learning sorting algorithms - Hill sort
Publish Date:2025/03/19 Views:52 Category:ALGORITHM
-
Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion
Things about the singleton design pattern
Publish Date:2025/03/19 Views:53 Category:ALGORITHM
-
The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i
The road to learning sorting algorithms - merge sort
Publish Date:2025/03/19 Views:158 Category:ALGORITHM
-
Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt
The road to learning sorting algorithms - merge sort (non-recursive implementatio
Publish Date:2025/03/19 Views:189 Category:ALGORITHM
-
In the article "Merge Sort", we introduced the principles and operation steps of merge sort, and finally implemented the sorting algorithm using PHP code. In the program, we used the principle of recursion to implement the algorithm. In fac
The road to learning sorting algorithms - quick sort
Publish Date:2025/03/19 Views:122 Category:ALGORITHM
-
Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste