Reputation: 459
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++ ?
Upvotes: 10
Views: 9673
Reputation: 2441
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.
Upvotes: 7
Reputation: 87959
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:
...
};
Upvotes: 4