Homework 8 The following code is a C++ example of a very limited implementation of a Linked List. It 1 answer below »

Need your ASSIGNMENT done? Use our paper writing service to score better and meet your deadline.


Order a Similar Paper HERE Order a Different Paper HERE

Homework 8
The following code is a C++ example of a very limited implementation of a Linked List. It is
written as a class wrapper for a Node structure and the functions to create a list, add values, and
show the contents. Also note the destructor will eliminate the list elements from memory.

1. class List {
2. struct Node {
3. int data;
4. Node * next;
5. };
6.
7. Node * head;
8.
9. public:
10. List() {
11. head = NULL;
12. }
13.
14. ~List() { // delete the list
15. while(head != NULL) {
16. Node * n = head->next;
17. delete head;
18. head = n;
19. }
20. }
21.
22. void add(int value) {
23. Node * n = new Node;
24. n->data = value;
25. n->next = head;
26. head = n;
27. }
28.
29. void show(){
30. while(head !=NULL) {
31. Node * n = head->next;
32. cout<< head->data <<“, “;
33. head = n;
34. }
35. cout << endl;
36. }
37.
38. };
39.
Illustration 1: Linked List Class

Illustration 2 is a main program which adds 7 values to the list and then shows the contents.
40. int main() {
41. List MyList;
42.
43.MyList.add(5);
44.MyList.add(12);
45.MyList.add(24);
46.MyList.add(32);
47.MyList.add(47);
48.MyList.add(54);
49.MyList.add(65);
50.
51.MyList.show();
52. return 0;
53.}
Illustration 2: Step 1. Main function
Step 1. Put the two pieces of code together in a Code::Blocks C++ console application and run the
program to print out the results. Screen capture the output and turn for Step 1.
Note: #include <> statements for libraries will have to be added plus A????1using std::A????1 declarations.
Question 1. Why does the data print out in the sequence that it does?
Step 2. Modify the List class in Illustration 1 to be a templated class. Use the ‘template’ keyword
to allow the class to accept any type of data for the list. Then use the following code for the main
function and print out results. Screen capture the output and turn in for Step 2.

54. int main()
55.{
56. // create first list
57. List<int> MyList;
58.
59.MyList.add(5);
60.MyList.add(12);
61.MyList.add(24);
62.MyList.add(32);
63.MyList.add(47);
64.MyList.add(54);
65.MyList.add(65);
66.
67. cout << “Here is my first list ” << endl;
68. MyList.show();
69.
70. // Create second list
71. List<string> MyStringList;
72.
73.MyStringList.add(“First String”);
74.MyStringList.add(“Second String”);
75.MyStringList.add(“Third String”);
76.MyStringList.add(“Fourth String”);
77.MyStringList.add(“Fifth String”);
78.
79. cout << “Here is my Second list ” << endl;
80.MyStringList.show();
81. return 0;
82.}
Illustration 3: Step 2. Main function

Reference: http://stackoverflow.com/questions/397895/how-could-i-create-a-list-in-c