Lab Exercises - Lists, Arrays and Trees
In questa pagina 14
Problem sets from the lab sessions (decks on lists, stacks/queues, arrays and BSTs). Theory: Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →, Sorting Linked ListsA linked list can be sorted with bubble, insertion, quick or merge sort by relinking nodes instead of copying data; merge sort with a slow/fast split is the cleanest on lists.Sorting Linked Lists →, Stacks and Queues in CA stack is LIFO (push/pop at the top), a queue is FIFO (enqueue at the rear, dequeue at the front); both can be built on an array or on a linked list, all operations in constant time.Stacks and Queues in C →, Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C →. The slides give statements, declarations and skeletons; complete solutions are given only where stated below. Where an answer is "worked out here", it is not on the slides.
A. Lists
A1. List of cities
Manage a linked list of cities, each with name, size (square kilometers) and population. Input: a CSV file (cities_size_population.csv), one city per row, fields separated by a semicolon; the file name is the first program argument. Create the list from the file, then display a menu:
- Add a city (size and population).
- Display all cities.
- Find the largest city (and its size).
- Find the most populated city (and its population).
- Delete a city by name.
- Order the list in ascending order of population.
- Order the list in ascending order of size.
- Exit.
Declarations and skeleton from the slides:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROW 127
#define MAX_LEN 63
#define POPULATION 0
#define SIZE 1
// Node structure for a capital city
struct Capital {
//char name[MAX_LEN+1];
char* name;
double size; // in square kilometers
long population;
struct Capital* next;
};
int main(int argc, char *argv[]) {
struct Capital* head = NULL;
int choice;
char name[MAX_LEN+1]; //if not using char * data type in the Capital node
//check argc
// open input file and check
// read input file + create linked list
// display menu and return user choice
// switch (choice) case invoking chosen function managing invalid choicesFunction prototypes:
void addCapital(struct Capital** head);
struct Capital* addCapitalSizePopulation(struct Capital* head, char *name, double size, long population);
void displayCapitals(struct Capital* head);
void findLargestCapital(struct Capital* head);
void findMostPopulatedCapital(struct Capital* head);
void deleteCapital(struct Capital** head, char* name);
struct Capital* read_cities(FILE* fi);
int bubbleSort(struct Capital** ptr, unsigned int order);
int displayMenu();Hints in the code: name can be a char* (allocate it) or a fixed array; the order parameter of bubbleSort is POPULATION or SIZE; one sort function serves both orderings. The two orderings reuse the bubble sort on nodes from Sorting Linked ListsA linked list can be sorted with bubble, insertion, quick or merge sort by relinking nodes instead of copying data; merge sort with a slow/fast split is the cleanest on lists.Sorting Linked Lists →.
A2. Stack from a linked list: reverse a string
Read a sequence of characters and print them in reverse order with a stack managed by a linked list. Example: easy exercise -> esicrexe ysae. Suggested functions: listInizialization, createNode, push (twice in the skeleton: push of the characters, and the printing pass). Solution not on the slides.
A3. Queue from a linked list: print in order
Read a sequence of characters and print them in reading order with a queue managed by a linked list. Functions: queueInizialization, createNode, enQueue, deQueue. Solution not on the slides.
A4. Stack with middle-element operations
Implement a stack with, all in O(1): Push, Pop, FindMiddle (retrieve the middle element), DeleteMiddle (remove it). Requirements: use a doubly linked list; write a main to test it. (The slides do not give the technique; a doubly linked list lets you step the middle pointer in both directions.)
A5. Palindrome check with a queue and a stack
Check whether a string is a palindrome using both a stack and a queue implemented with linked lists: push/enqueue each character into both; then compare the elements popped from the stack with those dequeued from the queue. "madam" -> Palindrome; "hello" -> Not a Palindrome. (A stack returns characters in reverse order, the queue in original order: they match one by one only if the string reads the same both ways.)
A6. List of cars
Create a list of cars from cars.csv (name, plate, registration year, power; semicolon-separated). The file name is the 1st program argument. Print the list, then order it according to the 2nd program argument (0: car name, 1: plate, 2: registration year, 3: power) and print again. Use an enum for the ordering parameter.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME 21
#define MAX_PLATE 11
#define MAX_ROW 81
struct carRegister
{
char carName[MAX_NAME + 1];
char carPlate[MAX_PLATE + 1];
int regYear;
int power;
struct carRegister* next;
};
int main(int argc, char *argv[]) {
enum order param = POWER;
struct carRegister* headList = NULL;
//check argc
//param variable value update
//read input file and list creation
//print the list
//order the list
//print the listThe slide uses enum order with a value POWER; the enumerators for the other three keys are not shown (they correspond to the four values 0-3 of the argument).
A7. Golf scores (doubly linked list)
Record golf tournament results: enter name and score of each player as the player finishes. It must be possible to:
- print names and scores in order by ascending or descending score;
- given a player's name, print the other players with the same score;
- after each new tournament entry, sort the list in descending order of scores.
A doubly linked list serves both print directions.
A8. Exam booklet (linked list)
A student manages up to 30 exams. Each exam: course name (max 256 characters), teacher name (max 128), grade (18 to 30), date (dd/mm/yyyy), course code (max 8 alphanumeric characters). Menu, repeated until exit:
[i] insertion of new exam
[p] booklet printing
[s] search by code
[x] exiti: insert an exam at the bottom of the list;p: print all exams with all the details;s: ask a code, search the booklet, print the exam if present;x: exit.
A9. Even and odd lists
Read positive integers (greater than 0, maximum 100) from the file given as argument, terminated by 0. Count and print how many were entered. Build two singly linked lists: even numbers in ascending order and odd numbers in descending order. Print the number of elements and the elements of each list, one list per row. Run it on sequence1.txt and sequence2.txt (in input.zip). Hint: ordered insertion as in Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →, with opposite comparisons for the two lists.
B. Arrays
B1. Class of students (array of records)
structure element {
char surname[32];
char name[32];
int age;
};(sic: the slide writes structure; in C it is struct element.) The program takes as argument the number of students (no more than 20) and reads surname, name (at most 31 characters) and age from the keyboard. Then it prints the records in ascending order of age, stores them in that order in a temporary file, and prints the name of the file. It must handle errors in reading data and in writing the file.
Input for argument 5:
Einstein Albert 120
Marconi Guglielmo 168
Volta Alessandro 25
Fermi Enrico 60
Eulero Sara 23Expected output:
Surname: Eulero
Name: Sara
Age: 23
Surname: Volta
Name: Alessandro
Age: 25
Surname: Fermi
Name: Enrico
Age: 60
Surname: Einstein
Name: Albert
Age: 120
Surname: Marconi
Name: Guglielmo
Age: 168
Records stored in file C:\Users\<user>\AppData\Local\Temp\ufh0.0(the last line shows a temporary file name generated by the system; the sample record for age 60 is renamed here.)
B2. Pairs with slope 1
Read blank-separated positive integers from the file given as argument into an array a of length n (maximum 100) and print all pairs i < j (i different from j) satisfying: absolute value of (a[i] - a[j]) / (i - j) equals 1. Input: one row with the n integers. Output: one pair per line.
For sequence1.txt: 10 15 8 20 14 25 19 28 12 4 22 17 the program prints the values and the indexes:
(10 - 8):(0 - 2)
(10 - 14):(0 - 4)
(8 - 17):(2 - 11)Check on the first: |10 - 8| / |0 - 2| = 2 / 2 = 1. Sub-problems listed on the slide:
- define how the array that stores the integers is managed;
- check the program arguments;
- open the file passed as argument for reading;
- loop that reads every integer;
- loop (over index pairs) that checks the condition and prints the result.
C. Trees
C1. Airports in a BST
Read up to 100 airports from a file (name passed as argument), one per row with three fields separated by ;: airport name, daily flights (departures plus arrivals), weekly flights. The first row holds the field names. Store them in a BST ordered by weekly flights, using the given declaration:
typedef struct Node {
char* name; /* Airport, e.g., "Chicago O'Hare (ORD)" */
int daily_total; /* Daily Total Flights (Departures + Arrivals) */
int weekly; /* Weekly Flights (from CSV) */
struct Node* left;
struct Node* right;
} Node;Then:
- print a table of the BST nodes in ascending order of weekly flights (inorder);
- print a table of the first 10 nodes in descending order of weekly flights;
- print the height of the BST (maximum depth of any leaf from the root, i.e. length of the longest root-to-leaf path);
- export the BST back to a CSV file in the current order.
Run it on international_airports.csv and report the results. Traversals and insertion: Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C →, Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →.
C2. Delete the leaves of a BST
Read blank-separated integers from the file given as first argument, store them in a BST in ascending order of value, print the preorder traversal, delete the leaf nodes, print the preorder traversal again, then delete the whole BST before ending. Use the sample sequence files (those of B2).
Example: tree with root 4, children 2 and 5, node 2 with children 1 and 3, node 5 with right child 7.
Preorder before deleting leaf nodes: 4 2 1 3 5 7
Preorder after deleting leaf nodes: 4 2 5(only the nodes that were leaves at the start are removed: 1, 3 and 7; nodes 2 and 5 become leaves but stay.)
Sub-problems from the slides: define the node struct; function to create and initialize a node; function to insert; function for the preorder print; function to delete the leaves; function to delete the whole BST. In main: check the arguments; open the file; loop reading every integer; print preorder; delete the leaves; print preorder; delete the whole BST.
C3. BST search sequences and min/max
Two exercises of the tree deck, with a worked answer, are in Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C → (search of 825: only sequence B is possible; BST of 50, 37, 70, 22, 40, 68, 80, 13, 118, 97: min 13, max 118).
D. Quiz questions from the lab slides
The slides give only the questions. The answers below are worked out here, not taken from the slides.
| # | Question | Answer |
|---|---|---|
| 1 | Declare a function returning a pointer to an integer, taking two integer parameters | A: int* function(int a, int b); |
| 2 | What does int* getValue() { static int x = 42; return(&x); } return? |
C: a pointer to a static variable (it outlives the call) |
| 3 | Correct call of int* getNumber(); |
B: int* x = getNumber(); |
| 4 | Declare a constant integer | A: int const x = 10; |
| 5 | static vs extern on variables |
B: static preserves its value across calls, extern refers to an external variable |
| 6 | Allocate an array of 10 integers dynamically | B: malloc(10 * sizeof(int)) (D, calloc(sizeof(int), 10), also gives 10 ints, zeroed) |
| 7 | free() on a pointer not obtained from malloc/calloc |
B: undefined behavior |
| 8 | Insert at the beginning of a singly linked list | A: new node's next = current head, then update the head |
| 9 | Flexible array member struct S { size_t n; int data[]; };, room for k ints |
B: malloc(sizeof(*p) + k * sizeof(p->data[0])) |
| 10 | Array of five pointers to char |
B: char *ptr[5]; |
| 11 | char (*x) (char*); what is x? |
c: a pointer to a function (taking char*, returning char) |
| 12 | Which leads to undefined behavior: uninitialized automatic variable read; free with an array address; arr[10] on a 10-element array |
d: all of the above |
| 13 | unsigned char x = 250, y = 10; unsigned char z = x + y; printf("%u\n", z); |
prints 4: the sum 260 is converted back to unsigned char (260 modulo 256) |
| 14 | BST search sequence for 825 (A-D on the lab slide, A-E on the tree slide) | B (see Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C →) |
Other questions on the slides, with the notes of the course:
- Reverse a string with subscripts (no pointers). Solution on the slide:
int main()
{
char s[] = "This is a sample string";
int i;
for (i = strlen(s) - 1; i >= 0; i--){
printf ("Character %d = %c\n", i, s[i]);
}
return 0;
}(needs <stdio.h> and <string.h> for printf and strlen.)
- Size of a boolean in C (options 1 byte, 1 bit, 2 bit, 16 byte): in practice 1 byte, since a byte is the smallest addressable unit.
- Valid places for
break: inside loops and inside aswitch. - Why
fflush(stdin)is undefined behavior:fflushis defined for output streams, not forstdin; the correct pattern is to read and discard characters up to the newline, e.g.int c; while ((c = getchar()) != '\n' && c != EOF) ;. - Fix
int *make(void) { int x = 42; return &x; }:xis automatic, so its address is invalid after the return; make itstatic(as in question 2) or allocate withmallocand let the callerfree.
E. Control-structure exercises (same lab deck)
- Switch case and ternary operator: read a number and say whether it is positive, negative or zero using
switchand the ternary operator (the slide says it is not the recommended way, just for learning). Example: input53->53 is positive. - Menu-driven calculator with
switchand functions: add, subtract, multiply, divide. Input format<number 1> <operator> <number 2>; example input8.5 - 5-> output3.5.
Versione ripasso
- Every program: check
argc, open the file and test the result, loop reading values, free dynamic memory. Problem sets on the slides give statements and skeletons only; the answers marked "worked out" are not on the slides. - Cities list (A1):
struct Capital { char* name; double size; long population; struct Capital* next; };, file name is the first argument,;-separated CSV. Menu: add, display, largest by size, most populated, delete by name, sort by population or size, exit. OnebubbleSort(&head, order)serves both orders, withPOPULATIONorSIZE. - Prototypes of the cities program:
struct Capital* read_cities(FILE* fi);,void deleteCapital(struct Capital** head, char* name);,int bubbleSort(struct Capital** ptr, unsigned int order);,int displayMenu();. The menu loop reads achoiceand calls the function with aswitch, rejecting invalid choices. - Cars list (A6):
struct carRegisterwithcarName,carPlate,regYear,power. The second argument (0 to 3) selects the sort key through anenum order(name, plate, year, power), printed before and after the sort, as inenum order param = POWER;. - Stacks and queues (Stacks and Queues in CA stack is LIFO (push/pop at the top), a queue is FIFO (enqueue at the rear, dequeue at the front); both can be built on an array or on a linked list, all operations in constant time.Stacks and Queues in C →): reverse a string with a stack (
easy exercise->esicrexe ysae); keep reading order withenQueue/deQueue; palindrome check with a stack and a queue fed with the same characters ("madam"yes,"hello"no); stack withPush,Pop,FindMiddle,DeleteMiddlein O(1) on a doubly linked list. - Golf scores (A7): doubly linked list, printed ascending or descending, names with the same score, re-sorted by descending score after each insertion.
- Exam booklet (A8): at most 30 exams, menu
[i]insert at the bottom,[p]print all,[s]search by code,[x]exit. - Even and odd (A9): read positive integers up to 100 until a 0. Even list ascending, odd list descending, built with ordered insertion (Linked Lists in CA linked list is a chain of dynamically allocated nodes, each holding data and a pointer to the next one; insertion and deletion only relink pointers, but access is sequential.Linked Lists in C →): the two lists use opposite comparisons.
- Students array (B1):
struct element { char surname[32]; char name[32]; int age; }, at most 20 records, sort by age, print, write to a temporary file, check read and write errors. - Slope-1 pairs (B2): for
i < j, print the pairs with|(a[i] - a[j]) / (i - j)| == 1. Sample10 15 8 20 14 25 19 28 12 4 22 17gives(10 - 8):(0 - 2), since |10 - 8| / |0 - 2| = 1. - Airports BST (C1):
typedef struct Node { char* name; int daily_total; int weekly; struct Node* left; struct Node* right; } Node;ordered byweekly. Inorder table ascending, first 10 nodes in descending order, height (longest root-to-leaf path), export to CSV (Trees in CA tree is a set of nodes with a root and a unique predecessor per node; in C a binary search tree uses a struct with two child pointers and recursive search, insertion at a leaf, three-case deletion and four traversals.Trees in C →, Tree TraversalsPreorder visits a node before its subtrees (top-down), postorder after them (bottom-up); both run in time proportional to the number of nodes plus the cost of the visits, and are design patterns for algorithms on trees.Tree Traversals →). - Delete leaves (C2): insert integers in a BST, print preorder, delete the nodes that are leaves at the start, print preorder again, delete the whole tree. Example:
4 2 1 3 5 7becomes4 2 5(1, 3 and 7 go; 2 and 5 become leaves but stay). - Control exercises (E):
switchplus ternary for positive, negative, zero (53 is positive); a calculator with<number> <operator> <number>and8.5 - 5giving3.5. - Quiz (worked out):
int* f(int a, int b);;int const x = 10;;malloc(10 * sizeof(int));freeon a non-heap pointer is undefined behavior; head insertion = link the new node to the head, then move the head; flexible array membermalloc(sizeof(*p) + k * sizeof(p->data[0]));char *ptr[5];;char (*x)(char*)is a pointer to function;unsigned char250 + 10 prints 4 (260 mod 256);staticlocal returns a pointer that outlives the call. - Typical errors: returning the address of a local variable;
fflush(stdin)(undefined: discard input with agetcharloop);arr[10]on a 10-element array; uncheckedmallocorfopen.