Problem title
Difficulty
Avg time to solve

Insertion In Doubly Linked List
Easy
15 mins
Deletion In Doubly Linked List
Easy
15 mins
Insertion In A Singly Linked List
Easy
15 mins
Height of Binary Tree
Easy
15 mins
Insertion In Circular Linked List
Easy
12 mins
Count Numbers With Equal First and Last Digit
Moderate
15 mins
Count Numbers Containing Given Digit K Times
Moderate
30 mins
Rotate Clockwise
Easy
15 mins
Prime Digit Sum
Hard
45 mins
Ninja And The Clan
Moderate
24 mins

Insertion In A Singly Linked List

Difficulty: EASY
Contributed By
Avg. time to solve
15 min
Success Rate
90%

Problem Statement

You are given a Singly Linked List of ‘N’ positive integers. Your task is to add a node having the value ‘VAL’ at position ‘POS’ in the linked list.

Note:
Assume that the Indexing for the linked list starts from 0.
EXAMPLE:
Input: ‘N’ = 5, 'LIST' = [1, 1, 2, 3, 4, -1], ‘VAL’ = 2, ‘POS’ = 1.

Output: 1 -> 2 -> 1 -> 2 -> 3 -> 4 

Here in the given list we can see that the node having value 2 is inserted at position 1.
Input Format :
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 

The first line of each test case contains an integer, ‘N’, denoting the number of nodes in the linked list.

The third line of the test case contains ‘N + 1’ space-separated integers which are the nodes of the linked list and each line ends with -1 to indicate that the sublist is over. Thus, -1 will never be a linked list element.

The fourth line of each test case contains two spaced integers ‘VAL’ and ‘POS’ denoting the value of the node and the position at which the node have to be inserted respectively.
Output format :
The first and only line of each test case in the output contains the linked list after inserting a node having the value ‘VAL’ at position ‘POS’ in the linked list.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= ‘T’ <= 10 
1 <= ‘N’ <= 10^4 
0 <= ‘POS <= N  
1 <= ‘data’, 'VAL' <= 10^7

Where 'N' is the size of the singly linked list, and ‘data’ is the Integer data of the singly linked list.

Time Limit: 1 sec
Sample Input 1 :
2
5
1 1 2 3 4 -1
2 1
1
1 -1
3 1
Sample Output 1 :
1 2 1 2 3 4
1 3
Explanation Of Sample Input 1 :
For the first test case,
‘N’ = 5, 'LIST' = [1, 1, 2, 3, 4, -1], ‘VAL’ = 2, ‘POS’ = 1.
After inserting the node having value = 2 at position 1 the list will be:
1 -> 2 -> 1 -> 2 -> 3 -> 4.

For the second test case,
‘N’ = 1,  'LIST' = [1, -1], ‘VAL’ = 3, ‘POS’ = 1.
After inserting the node having value = 3 at position 1 the list will be:
1 -> 3.
Sample Input 2 :
2
2
1 2 -1
3 0
2
3 4 -1
5 1
Sample Output 2 :
3 1 2  
3 5 4
Reset Code
Full screen
copy-code
Console