-4

I went to an interview last month the interviewer asked an interesting question: Can we write linked list using class not using structure? I said yes and also I wrote something like the code below. Can anyone explain whether it is right or wrong?

class list {    
public:    
   int a;  
   class *list;
 };
7
  • 2
    There is no much difference between struct and class. Only default visibility. Commented Jan 29, 2018 at 10:03
  • 2
    The only difference between class and struct is that the default access level is private in classes and public in structures. Commented Jan 29, 2018 at 10:03
  • The difference between struct and class is only in default access specifier. Also I'd answer "Yes we can, but we shouldn't reinvent wheel without strong reason" Commented Jan 29, 2018 at 10:10
  • You could use parallel arrays, ugly but it would work. I wouldn't accept an answer using a class, there's no essential difference between a class and a struct. Commented Jan 29, 2018 at 10:10
  • 1
    Someone indeed suggested it, but it was you who clicked "yes" and closed this question. Are you having buyer's remorse? Commented Jan 29, 2018 at 10:21

1 Answer 1

2

You can write data structures such as linked lists using both classes and structures. Terms like class and struct mean the same thing in C++. The only thing that is different is the default visibility which is private for classes and public for structures. That being said your class is ill-formed, it should be:

class list {    
public:    
   int a;  
   list* l; // list* instead of class* here
};

When using the keyword struct you can leave out the public: specifier:

struct list {
   int a;  
   list* l;
};

Please note there are already ready made containers in the Standard C++ Library.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.