Menu
Coddy logo textTech

Practice #4

Lesson 13 of 14 in Coddy's Doubly Linked List - Data Structures Series #6 course.

challenge icon

Challenge

Easy

Write a function moveToFront that gets an integer array arr (the values of a doubly linked list) and an integer value, finds the first occurrence of value, and moves that node to the front of the list. Return the resulting array.

If value is not in the list, return the array unchanged.

Use a doubly linked list to solve this problem!

You must use the DoublyLinkedList class (provided in doublylinkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' reverse, slicing, sort, or stdlib list operations to compute the result.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"

int main() {
    char line1[8192];
    char line2[64];
    if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
    if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
    int arr[4096];
    int len = 0;
    char* tok = strtok(line1, " \t\r\n");
    while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    int n = atoi(line2);
    int rs = 0;
    int* r = moveToFront(arr, len, n, &rs);
    for (int idx = 0; idx < rs; idx++) {
        if (idx > 0) printf(" ");
        printf("%d", r[idx]);
    }
    printf("\n");
    return 0;
}

All lessons in Doubly Linked List - Data Structures Series #6