ExerciseFocus
0. Remove IfUpdate links and free removed nodes
1. Insert AtAllocate and insert a node at a specified position
2. SchedulerMaintain linked queues as processes change state
3. MkdirCreate, traverse, and free a tree of directories

Getting Started

Open your WebTop in Entainer.
Run cs1010, select Download CS1010 content, then choose Volumes and Volume 8.
Work in the downloaded Volume 8 directory.

Write your answers in student.c inside each exercise’s directory.

  • We handle reading input and program setup, so you do not need to change main.c or the header files.
  • You may assume allocations succeed and that list lengths, queue counts, and allocation sizes fit their corresponding types.
  • All lists and trees are finite and have no cycles or shared nodes.

The Makefiles enable ASan and UBSan.
Consider revisiting Tutorial 5: Sanitisers if you need help understanding a sanitiser report.

0. Remove If

Focus

Update a caller’s list head and free nodes without losing the rest of the list.

Introduction

Assume we have a linked list of characters.
That is, “aBCdE” will be represented as a linked list a -> B -> C -> d -> E -> nullptr.

Your task: remove nodes representing uppercase letters from that linked list.
Removing a node means changing the links so the remaining nodes still form a list.
For example, removing uppercase letters from aBCdE should leave a valid linked list that represents ad.
If the first node is removed, the head of the list must change too.

Your Task

In 0-remove-if/student.c, implement:

void remove_if_upper(LinkedList **list);
void free_list(LinkedList *list);

The node type in student.h is:

typedef struct LinkedList {
    char c;
    struct LinkedList *tail;
} LinkedList;

remove_if_upper receives a pointer to the variable holding the head of the list.
Remove every node containing an uppercase English letter (A through Z).
Free each removed node and update *list to the remaining head.
Preserve the original nodes, characters, and order of everything else.
Do not allocate replacement nodes.
The list may be empty (*list == nullptr).
If every node is removed, set *list to nullptr.

free_list frees every node in the list it receives.
It must also handle nullptr.
We call it after printing the remaining characters,
so do not free retained nodes in remove_if_upper.
Neither function prints anything or returns a value.
Input characters are ASCII and exclude the null character and newline.
Spaces, lowercase letters, digits, and punctuation are retained.

Running and Testing

  • To compile: run make in 0-remove-if
  • To test: run make test
  • To run: run ./remove-if, enter a line of characters, then press Enter

The program prints the remaining characters followed by a newline.
A blank input line represents an empty list.

Examples

Example 1

Input

aBCdEf!

Output

adf!

The nodes holding B, C, and E are freed.
The other nodes remain in their original order.
For input ABC, all three nodes are freed and the output is a blank line.
A blank input line also produces a blank output line.

1. Insert At

Focus

Add a node while preserving the existing linked list.

Introduction

A linked list with three nodes has four possible insertion positions.
Position 0 is before the first node, position 1 is after the first node,
and position 3 is after the last node.
In general, a list of length has positions 0 through , inclusive.
An empty list has just one insertion position: 0.

Your Task

In 1-insert-at/student.c, implement:

LinkedList *insert_at(LinkedList *list, int value, size_t position);

The node type in student.h is:

typedef struct LinkedList {
    int value;
    struct LinkedList *tail;
} LinkedList;

Allocate one new node containing value and insert it before the node at position.
If position equals the list’s length, append the new node.
Return the head of the resulting list, which may differ from the original head.
Retain all existing nodes and their relative order.
Do not free or replace them.
The position is always valid, and values fit in int.
For an empty list (list == nullptr), position 0 produces a one-node list.

The only required public function is insert_at.
Your function does not print anything.
We print the resulting list and free every node afterwards.
debug_print_list, declared in student.h, can help you inspect a list on standard error while debugging.

Running and Testing

  • To compile: run make in 1-insert-at
  • To test: run make test
  • To run: run ./insert-at

Enter the list’s integers on the first line, separated by spaces or commas.
A blank first line represents an empty list.
Enter the value to insert on the second line and its position on the third line.
Press Enter after each line.
The displayed list has -> after each value and ends with NULL and a newline.

Examples

Example 1

Input

1 2 3
9
2

Output

1->2->9->3->NULL

There are two existing nodes before insertion position 2.
The new node goes between the nodes holding 2 and 3.
For the same initial list, position 0 inserts before 1 and position 3 inserts after 3.

Example 2

Input (the first line is blank)

 
7
0

Output

7->NULL

The returned head points to the only node in the new list.

2. Scheduler

Focus

Implement linked list operations to support queueing operations.

Introduction

An operating system typically has a queue (that’s a lie, it has many) to schedule processes to be run. Each process is identified via a process id or pid for short (from 1 through INT_MAX.). We’re going to build a process scheduler. In our simple model of a process, it can be in 1 of 3 possible states: running, paused or killed.

A scheduler, in some sense, has to keep track of the currently running processes, and the currently paused ones. We will do this in the form of a queue. Why? Because running processes need to take turns sharing the CPU (and other hardware). So in a queue (where there is a front and a back), the idea is that the process at the front of the queue is the one that currently gets to enjoy using the CPU (and other hardware). Once the CPU has decided “OK TIME’S UP”, it should move the current process to the “back of the queue” and give the process that’s next in line their share of the hardware.

There are other complicated mechanics, for example sometimes processes might be blocked on hardware events yadda yada. So those processes might just be put to a paused queue instead.

Anyhoo, we’re just here to make a baby scheduler.

Your Task

student.h defines:

typedef struct LinkedList {
    int process_id;
    struct LinkedList *tail;
} LinkedList;
 
typedef struct ProcessScheduler {
    LinkedList *run_queue;
    LinkedList *pause_queue;
} ProcessScheduler;

We provide init_scheduler, which initializes both queues to nullptr.
Implement these functions in 2-scheduler/student.c:

void shutdown(ProcessScheduler *scheduler_ptr);
int kill(ProcessScheduler *scheduler_ptr, int pid);
void list_running(ProcessScheduler *scheduler_ptr);
void list_paused(ProcessScheduler *scheduler_ptr);
int currently_running(ProcessScheduler *scheduler_ptr);
int run(ProcessScheduler *scheduler_ptr, int pid);
int pause(ProcessScheduler *scheduler_ptr, int pid);
int num_running(ProcessScheduler *scheduler_ptr);
int num_paused(ProcessScheduler *scheduler_ptr);

run places the specified process at the back of the running queue.
Its return code tells us where that process was before the call:

Previous StateEffectReturn Code
RunningMove it to the back of the running queue0
PausedMove it from the paused queue to the back of the running queue1
Any other caseCreate it at the back of the running queue2

pause moves a running process to the back of the paused queue.
Repeatedly pausing an already paused process leaves its position unchanged.
Pausing an unknown PID does not create a process:

Previous StateEffectReturn Code
RunningMove it to the back of the paused queue0
PausedLeave both queues unchanged1
Any other caseLeave both queues unchanged-1

kill removes a process and frees its node.
Return 0 if it was running, 1 if it was paused, or -1 if it did not exist.
Removing or moving a process preserves the relative order of all other processes.
A process must never remain in both queues, and moving it must not leak its old node.

currently_running returns the PID at the front of the running queue,
or -1 if that queue is empty.
num_running and num_paused return the number of processes in the corresponding queue.
These functions do not change either queue.

list_running and list_paused print the corresponding queue from front to back,
one PID per line, with a newline after each PID.
An empty queue produces no output.
Only these two functions print anything; we print the other functions’ return values.

shutdown frees all nodes in both queues and sets both heads to nullptr.
Do not free scheduler_ptr itself.
It must be safe to call shutdown repeatedly,
and the scheduler can be used again afterwards.
All nodes allocated for processes must eventually be freed when killed or shut down.

Running and Testing

  • To compile: run make in 2-scheduler
  • To test: run make test
  • To run: run ./scheduler

Enter one command per line and finish the input with $.
Commands are case-insensitive.
For commands with a PID, put a space between the command and its positive integer argument.

CommandAction
R pid, P pid, K pidCall run, pause, or kill, then print its return code
LR, LPPrint the running or paused queue
CPrint the currently running PID
NR, NPPrint the number of running or paused processes
SShut down the scheduler; more commands may follow
$Finish the input

A shutdown prints nothing.
Use S after your last operation to free any remaining processes.

Examples

Example 1

Input

R 10
R 20
P 10
C
LP
R 10
LR
K 20
C
S
$

Output

run 10: return code 2
run 20: return code 2
pause 10: return code 0
currently_running: 20
10
run 10: return code 1
20
10
kill 20: return code 0
currently_running: 10

After pausing 10, the running queue contains only 20.
Running 10 again puts it behind 20.
Killing 20 then makes 10 the currently running process.
The final shutdown frees 10’s node.

If the paused queue contains 10 followed by 20, P 10 returns 1
and leaves that order unchanged.
For an unknown PID, P pid and K pid return -1 without changing the queues.
Immediately after initialization or shutdown, both counts are zero,
listing either queue prints nothing, and C prints currently_running: -1.

3. Mkdir

Focus

Represent a directory hierarchy as a tree and manage its memory.

Introduction

Directories form a tree: a directory can contain other directories, and each of those can contain more directories. We will simulate a small directory hierarchy in memory.
The base directory is named ..
For example, notes/week1 names a directory week1 inside notes inside the base directory.
This exercise does not create or inspect directories on your computer, so don’t get too excited or scared.

Our mkdir behaves like creating one directory at a time. Its parent must already exist so
it does not create missing parents automatically, unlike mkdir -p in the shell.
Our ls recursively lists a directory and its descendants, as described below.

Your Task

student.h defines:

typedef struct Vector {
    struct Tree *sub_directories;
    size_t size;
    size_t capacity;
} Vector;
 
typedef struct Tree {
    char *name;
    Vector sub_directories;
} Tree;
 
typedef struct DirectoryManager {
    Tree *base_folder;
} DirectoryManager;

Each Tree stores its own directory name, not its full path. Its Vector stores an array of child Tree values. size is the number of children currently stored; capacity is the number of array elements for which memory has been allocated. Only the first size entries are children.
The array may move when it grows, so a pointer into that array must not be used after an operation that reallocates it. We have helper functions to help you manipulate Vector. You can see them at the top of student.c.

We provide init_directory_manager, which creates an empty base directory named ..
Complete these functions in 3-mkdir/student.c, using the vector helpers there as appropriate:

int mkdir(DirectoryManager *dm_ptr, const char *path);
int ls(DirectoryManager *dm_ptr, const char *path);
void delete_directory_manager(DirectoryManager *dm_ptr);

The examples below use null-terminated paths relative to the base directory.
A directory name contains one or more ASCII letters, digits, hyphens, or underscores,
and names are case-sensitive. Use / to separate names, and allow an optionally single trailing /.
For example, notes/week1 and notes/week1/ identify the same directory.
The program passes . when you use L alone to list the base directory.
An optional leading ./ refers to the same base directory.
For example, notes/week1, ./notes/week1, and ./notes/week1/ identify the same directory.
This applies to both mkdir and ls.
Do not modify or retain pointers into path.
New directory names need their own allocated storage.

mkdir creates only the final directory in its path. Append it after the parent’s existing children.

Its return codes are:

ConditionEffectReturn Code
Parent exists and the final directory is newCreate the directory0
The directory already existsLeave the tree unchanged1
A parent directory does not existLeave the tree unchanged2

mkdir does not print anything.
Creating a child with the same name under a different parent is allowed.
A failed or duplicate creation must not alter the tree or leak memory.

ls returns 1 and prints nothing if the path does not exist. Otherwise, print the named directory first, then recursively print each child’s entire subtree in the order the children were created,
and return 0. Print one directory name per line, with no indentation or full-path prefix.
An existing directory with no children still prints its own name. Listing does not change the tree.
There is no sorting, wildcard matching, or file handling in this exercise.

delete_directory_manager frees every directory name and every child array,
as well as the allocated base node. Child nodes live inside their parent’s array; they are not separately allocated node pointers. Do not free dm_ptr itself. The program calls this function when it finishes, after which the manager is no longer used. Free any temporary allocations your functions create too. (You might segfault… it’s part of the journey. Don’t panic. We gave y’all lots of debugging tools for this reason 🤍.)

Running and Testing

  • To compile: run make in 3-mkdir
  • To test: run make test
  • To run: run ./directory

Enter one command per line and finish with $.
M path calls mkdir and then prints mkdir path: code.
L path calls ls and then prints ls path: code, after any names printed by ls.
L alone lists from ..
Command letters may be uppercase or lowercase; directory names keep their original case.

Examples

Example 1

Input

M notes
M notes/week1/
M notes/week1
M missing/week2
L notes
L missing
$

Output

mkdir notes: 0
mkdir notes/week1/: 0
mkdir notes/week1: 1
mkdir missing/week2: 2
notes
week1
ls notes: 0
ls missing: 1

The parent notes exists before notes/week1/ is created.
The trailing slash does not create a different directory.
Since missing does not exist, creating missing/week2 fails and creates neither directory.

Example 2

Input

M a
M b
M a/x
L
$

Output

mkdir a: 0
mkdir b: 0
mkdir a/x: 0
.
a
x
b
ls .: 0

Although b was created before x, listing finishes all of a’s subtree before visiting b.
For a newly initialized manager, L prints just . followed by ls .: 0.