How can the List class contain all types?

This question is part of the assignment for my data structures class. I will tell part of the description below.

Modify the List class (with a linked list as a backend) to support generics so that it can not only contain integers, but also other types, such as floats and characters. I have provided a new core function, as well as an output generated from my implementation. Hint: you only need to add one line and change one word in five lines. So it does not take you much time.

The problem I am facing is understanding the question, although it may seem quite simple for most of them, I can just think about it. He claims that I only need to add one line, and I assume that the line will be inserted into part of the following code:

class List
{
  private:
    struct Node
    {
        int data;
        Node *link;
    };

Now I'm not sure how I will add this last line, but I was thinking maybe I could do:

int, char, floating point data;

or is this not a valid way to do this? I know about 5 places elsewhere in the code that I will need to change, but the question really confuses me. Thank.

+3
source share
2 answers

will be

template <typename T>
class List {
  private:
   struct Node {
    T data;
    Node *link;
   }
}

Job?

+6
source

Unions combine different types of data in one place.

eg.

union combined_data {
int i;
float f;
};

you can say mixed_data.i = 42;

  mixed_data.f = 3.14;

- . : . () .

template<T>
class List
{
private:
    struct Node
    {
        T data;
        Node *link;
    };
};

List<int> intlist;

List<float> floatlist;
+1

All Articles