Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure or class which is better for linked list?

Tags:

c++

For the implementation of linked list which is better

Using structure

#include <iostream>

using namespace std;

struct Node {
    int data;
    Node* next;
};

Using class

class ListNodeClass
   {
   private:
      ItemType Info;
      ListNodeClass * Next;
   public:

      ListNodeClass(const ItemType & Item, ListNodeClass * NextPtr = NULL):
         Info(Item), Next(NextPtr)
            {
            };
      void GetInfo(ItemType & TheInfo) const;
   friend class ListClass;   
   };

typedef ListNodeClass * ListNodePtr;

Or is their any better way for doing linked list in C++ ?

like image 621
san45 Avatar asked Oct 05 '13 06:10

san45


2 Answers

The only one thing which class and struct makes differ in C++ is the default interface. if you write:

struct MyStruct
{
    int a;
}

and:

class MyClass
{
    int a;
}

the only one difference is a field in both them. In MyStruct field a is public and in MyClass field a is private. Of course you can manipulate them using public and private keywords in structs and classes both.

If you are programming in C++ you should use classes.

like image 73
pt12lol Avatar answered Nov 15 '22 17:11

pt12lol


A linked list is one thing, its nodes are another thing. The nodes are part of the implementation of the list. They should not be visible in the interface of a list so their form doesn't really matter. I would do this

class List
{
private:
    struct Node
    {
        int data;
        Node* next;
    };
public:
    ...
};
like image 36
john Avatar answered Nov 15 '22 16:11

john