Description
The purpose of this challenge is to manually create a linked list to understand its basic structure.
Requirements
- Write a struct called StateInfo. This struct will be used as a linked list node.
struct StateInfo { string abbv; string name; int population; StateInfo * next; };
- Create a function void show(StateInfo * ptr). This function will display each node’s information. This function shows the contents of all the nodes in the linked list. In this function,
- ptr will contain the address of the head (the first node in the linked list).
- Declare a pointer, StateInfo * curr. This pointer will start at the head of the list and will be used to traverse to the end of the list.
- Create a function int totalpop(StateInfo * ptr). This function will calculate the total population represented in the nodes of the linked list. The return value is the calculated total. In this function,
- ptr will contain the address of the head (the first node in the linked list).
- Declare a pointer, StateInfo * curr. This pointer will start at the head of the list and will be used to traverse to the end of the list.
- In main(), create a pointer StateInfo, StateInfo * head. This pointer will not be instantiated to a new StateInfo object. It will only be a pointer.
- In main(), create and instantiate a pointer variable, StateInfo * state1 = new StateInfo;
- Set state1’s properties to the following information: abbv: “CA”, name: “California”, population: 39400000
- Create and instantiate two more pointer variables, state2 and state3.
- Set state2’s properties to the following information: abbv: “OR”, name: “Oregon”, population: 4300000
- Set state3’s properties to the following information: abbv: “WA”, name: “Washington”, population: 7800000
- state1, state2 and state3 will represent 3 nodes of a linked list. Use each of their respective next properties to link them in the order of state1-state2-state3. Remember that state3->next will point to NULL. Remember to point head to state1.
- Call the show() function passing in head. You should see the 3 nodes’ information.
- Rearrange and reconnect the nodes in the order state3-state1-state2. Make sure that head points to the first node and the last node points to NULL
- Call the show() function passing in head. You should see the 3 nodes’ information in the rearranged order
- Call the totalpop() function passing in head to display the total population.
- Don’t forget to delete state1, state2 and state3. You do not need to delete head as it only held the address; it didn’t point to an instance of its own.
Sample Interaction
CA-California (population 39400000) OR-Oregon (population 4300000) WA-Washington (population 7800000) WA-Washington (population 7800000) CA-California (population 39400000) OR-Oregon (population 4300000) Total population: 51500000
CATALOG ID: CPP-CHAL00047
Print Requirements