Insert Before Value

Medium Singly Linked List: Insertion
Solve in Playground →

Problem Statement

Write a C program to insert a new node immediately before the first occurrence of a specific key value in a singly linked list.

Input Format

First line contains n. Second line contains n elements. Third line contains the target key value. Fourth line contains the new value to insert.

Output Format

Print the updated linked list separated by spaces.

Constraints

1 <= n <= 100

Sample Input

4
10 30 40 50
30
20

Sample Output

10 20 30 40 50

Explanation

Traverse while keeping track of the previous node to insert the new node right before the target node.

Starter Code

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

int main() {
    int n;
    if (scanf("%d", &n) == 1) {
        struct Node *head = NULL, *tail = NULL;
        for (int i = 0; i < n; i++) {
            int val;
            scanf("%d", &val);
            struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
            newNode->data = val;
            newNode->next = NULL;
            if (head == NULL) {
                head = newNode;
                tail = newNode;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        int target, insertVal;
        scanf("%d %d", &target, &insertVal);
        // Write your code here to insert before value
    }
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used