Assignment: Pointer Intro

This assignment is split into two pieces. The first piece is an actual program that should compile and execute as indicated. The second piece is a code segment only that does not have to compile.

Program 1:

Write a program that stores 50 doubles in a linked list, as discussed in class. Add a code segment to display the data fields of all 50 notes.

Recall that you should define a class Node with two public fields: one double value and one pointer to a Node. You should also provide two constructors, one without parameters to set the Node pointer to null, and another one with one double parameter to set the double field to that number and the node pointer to null. In other words:

class Node
{
   public: double data;
   public: Node *next;

   public: Node(void);    // sets the next pointer to null
   public: Node(double);  // sets next pointer to null and data field to input parameter
}

To do your program, I would suggest the following:

use three variables, all pointers to a Node, named ‘top’, ‘last’, and ‘temp’, and initialize them to null
make sure that ‘top’ always points to the first node, ‘last’ always points to the last node, and ‘temp’ is a temporary pointer.
use a for loop to create the 2000 nodes, and store some number in its data field

When designing the for loop, you should carefully check whether the first node should be handled separately, i.e. before the for loop. To help you write your little program, here are a few pictures indicating the states of the pointers at various stages.

Empty List:

corresponding code segment:
Node *top = 0, *temp = 0, *last = 0;

List with first node added:

Corresponding code segment:
temp = new Node(2.0);
top = last = temp;

List with a few nodes:

Corresponding code: the code can be found with the next picture, and really relates to both, this and the next picture.

List where a new node has just been created (via new) and added to the end of the existing list

Corresponding code segment (to the previous two pictures)
// creates the new node with temp pointing to it
  temp = new Node(2.0);
// resets  next pointer of the ‘old’ last node to point to the new node
  last->next = temp; 
// resets last to point to the new last node
  last = temp;

The main program should consist of two segments:

Segment 1:
create the first node
create the remaining 49 nodes and store doubles in them
Segment 2:
set temp to the top of the list
use temp to move from one node to the next, displaying the data field of each node

Program 2 Write some code segment to create the following picture (each of the blocks is a 'Node', as described in the previous program): Note: You can only use one variable named C to create this circular list.