简体   繁体   中英

Structure or class which is better for linked list?

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++ ?

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.

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:
    ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM