What is the complexity to insert a node at a specific position in a linked list?

Insert a node at a specific position in a linked list

Given a singly linked list, a position and an element, the task is to write a program to insert that element in a linked list at a given position.

Examples:

Input: 3->5->8->10, data = 2, position = 2 Output: 3->2->5->8->10 Input: 3->5->8->10, data = 11, position = 5 Output: 3->5->8->10->11
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: To insert a given data at a specified position, the below algorithm is to be followed:

  • Traverse the Linked list upto position-1 nodes.
  • Once all the position-1 nodes are traversed, allocate memory and the given data to the new node.
  • Point the next pointer of the new node to the next of current node.
  • Point the next pointer of current node to the new node.

Below is the implementation of the above algorithm.

C++




// C++ program for insertion in a single linked
// list at a specified position
#include
using namespace std;
// A linked list Node
struct Node {
int data;
struct Node* next;
};
// Size of linked list
int size = 0;
// function to create and return a Node
Node* getNode[int data]
{
// allocating space
Node* newNode = new Node[];
// inserting the required data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a Node at required position
void insertPos[Node** current, int pos, int data]
{
// This condition to check whether the
// position given is valid or not.
if [pos < 1 || pos > size + 1]
cout next;
}
size++;
}
}
// This function prints contents
// of the linked list
void printList[struct Node* head]
{
while [head != NULL] {
cout next;
}
cout 5->8->10
Node* head = NULL;
head = getNode[3];
head->next = getNode[5];
head->next->next = getNode[8];
head->next->next->next = getNode[10];
size = 4;
cout

Bài Viết Liên Quan

Bài mới nhất

Chủ Đề