-3

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;
 };
quamrana
  • 37,849
  • 12
  • 53
  • 71
Guna Sekaran J
  • 70
  • 1
  • 14
  • 2
    There is no much difference between `struct` and `class`. Only default visibility. – Michał Walenciak Jan 29 '18 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. – goodvibration Jan 29 '18 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" – devalone Jan 29 '18 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. – john Jan 29 '18 at 10:10
  • Actually someone said its repeated question no it's not repeated this is different my question is different kindly check it. https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c – Guna Sekaran J Jan 29 '18 at 10:18
  • 1
    Someone indeed suggested it, but it was you who clicked "*yes*" and closed this question. Are you having buyer's remorse? – StoryTeller - Unslander Monica Jan 29 '18 at 10:21
  • @GunaSekaranJ Questions like this are just meant to get you talking so the interviewer can learn something about how you think. They don't have right or wrong answers. Your answer is fine (coding errors apart) but it's a literal interpretation of the question. – john Jan 29 '18 at 10:22

1 Answers1

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.

Ron
  • 14,674
  • 4
  • 34
  • 47