CS 12 - Linked Lists
A linked list is a primitive data structure that allows you to store
items of the same type, like in an array, but with slightly easier
methods of re-ordering the data and adding new values at the beginning
of the list. The concept of a linked list is quite simple: each
node of a linked list has a piece of data, and a pointer to the
next node in the list. This way, if you have a pointer to the first
node in the list (called the "head"), you can follow through the list
to get to every value.
A common method of representing a Node for a linked list of integers
is as follows:
struct Node
{
int value;
Node* next;
};
Specs
This program will perform a couple very simple list operations. We
will do much more with linked lists in CS 14.
Your task is to read in an arbitrarily long list of integers, insert
them into the head of a linked list, find the minimum element,
remove that element, and then print out the list, now in reverse
order.
Hints
- A list ends when the next value of a Node is NULL.
- Any function that edits a list probably needs to return a pointer
to the head of the list (since the head may change). Make sure you
use that return value in the calling function.
- You will want to write a function Node* insertAtHead(Node*
head, int val) that takes in a pointer to the head of a linked
list, and a value to insert. It then allocates a new Node on the
heap, makes that node point to the head, and returns a pointer to the
new node as the new head of the list.
- You will want a function int findMin(Node* head) that
returns the value of the smallest element in the list. It may return
0 if the list is empty (that is, head is NULL).
- You should also write a function Node* remove(Node* head, int
val) that loops through the values in the list until it finds
val, and removes val (just the first instance, so
you can return afterward.). You'll want to keep a pointer to
the previous Node so you don't break the list into two chains. Try
drawing it on paper using boxes and arrows to understand what you need
to do.
- Finally, write a function that takes in a list and prints out each
element it comes to, one value per line.