Lab #2: Linked List
Objectives
- Know how to declare and build linked lists in C.
- Know how to recognize and implement classic linked list algorithms using iterative functions.
Context and preparation: We will use linked lists (unsorted, then sorted) to represent sets of integers. The classic set operations1 on integers will be implemented using classic iterative list algorithms.
IMPORTANT the 2 main causes of segmentation fault with linked lists:
: an uninitialized list
: accessing the fields of an empty cell (e.g., accessing P->val or P->next
when P=NULL).
Lab Questions
All questions should be tested as you go (calls in main), as usual!
From the Lecture (Unsorted Lists)
Difficulty: Rx- Declare a linked list.
- Write the function to create a linked list by prepending at the head.
- Write a function to print a linked list.
- Write a function that tests whether a linked list is sorted.
- Write a function to delete the head cell of a linked list.
- Write a function to deallocate a list.
- Test the previous functions. Verify with valgrind that there are no memory leaks at runtime.
Sorted Lists
Difficulty: RxWe will now maintain a sorted list without duplicates.
- Write an algorithm to insert an integer into a list sorted in ascending order. The insertion should only be performed if the element does not already exist in the list.
- Write a function that creates a sorted list of integers by reading from a file. The integers in the file may be negative and in any order.
Set Operations
Difficulty: HardWrite functions to:
- Test whether an arbitrary list contains no duplicates.
- Compute the union of two sets (i.e., the union of two duplicate-free lists).
- Compute the intersection of two sets.
- Convert an arbitrary list into a set (remove duplicates).
Footnotes
-
A set is a collection or grouping of distinct objects; these objects are called the elements of that set. ↩