CSCI 261 - Programming Concepts - Spring 2022

Lab 4A - Array vs Linked List

This lab is due by Tuesday, March 29, 2022, 11:59 PM.
As with all labs you may, and are encouraged, to pair program a solution to this lab. If you choose to pair program a solution, be sure that you individually understand how to generate the correct solution.


Instructions


In this lab, we are going to perform the same set of operations twice. First using a dynamically allocated array and next with a dynamically allocated Linked List. Perform the following steps in your program:

  1. Using a pointer, create an integer array with three elements.
  2. Prompt the user to enter the value for each element.
  3. Print out the contents of the array in order.
  4. Print out the contents of the array in reverse order.

Now, we'll repeat those same steps but use a Linked List. Begin by creating a struct to represent a Node, as discussed in class. Then create a pointer to a dynamically allocated Node. Recall that the new keyword will allocate an amount of memory on the free store equal to the datatype being requested. When we create a struct we are creating a custom datatype to use. Therefore, we can create a pointer to a Node as follows.

Node *pHead = new Node;

This pointer now points to a Node object. If we dereference the pointer (with *pHead), we then get the Node object. We can then access the individual components of the struct. For instance

(*pHead).value

Since this is such a common operation (to dereference a pointer and then access a member), we can use the arrow operator to access a member off of a pointer.

pHead->value

We'll now want to make two more Nodes and chain them together into a Linked List. Our pHead pointer will still refer to the first element of the list and we can now advance through each element via the pNext member.

With our linked list in place, we can ask the user to enter the value for each element in the list. Then we'll print out the elements in order of the list and in reverse order.

Don't forget to deallocate all your memory when you are done.


Lab Submission


Submit your main.cpp file(s).

You will submit your solution to this lab with the rest of Set4. Detailed instructions for doing this are posted in Assignment 4.


This lab is due by Tuesday, March 29, 2022, 11:59 PM.
As with all labs you may, and are encouraged, to pair program a solution to this lab. If you choose to pair program a solution, be sure that you individually understand how to generate the correct solution.