Delete a Value

Lab C Intermediate 20 points

Build a list from n integers (in order), then delete the first node whose value equals x. Print the list (or empty) and deleted / not found.

Input

n, the integers, then x.

Output

Two lines.

Example

Input

5
1 2 3 2 5
2

Output

1 3 2 5
deleted
Sample input available Sample output available
Editor
C

Hints

Track the previous node so you can unlink the current one.

Deleting the head is a special case.

Solution explanation

Unlinking means pointing the previous node past the deleted one, then freeing it.

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

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

int main() {
    int n, x;
    struct Node *head = NULL, *tail = NULL;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &x);
        struct Node *node = malloc(sizeof(struct Node));
        node->value = x;
        node->next = NULL;
        if (head == NULL) head = node;
        else tail->next = node;
        tail = node;
    }
    scanf("%d", &x);
    struct Node *prev = NULL, *cur = head;
    while (cur != NULL && cur->value != x) {
        prev = cur;
        cur = cur->next;
    }
    int deleted = 0;
    if (cur != NULL) {
        if (prev == NULL) head = cur->next;
        else prev->next = cur->next;
        free(cur);
        deleted = 1;
    }
    if (head == NULL) printf("empty");
    for (struct Node *p = head; p != NULL; p = p->next) printf("%d ", p->value);
    printf("\n%s\n", deleted ? "deleted" : "not found");
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD