简体   繁体   English

对链表更好的结构或类?

[英]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++ ? 或者他们是否有更好的方法在C ++中进行链表?

The only one thing which class and struct makes differ in C++ is the default interface. classstruct在C ++中唯一不同的是默认接口。 if you write: 如果你写:

struct MyStruct
{
    int a;
}

and: 和:

class MyClass
{
    int a;
}

the only one difference is a field in both them. 唯一的区别是两者都是a领域。 In MyStruct field a is public and in MyClass field a is private. MyStruct字段中, a是公共的,在MyClass字段中, a是私有的。 Of course you can manipulate them using public and private keywords in structs and classes both. 当然,您可以在结构和类中使用publicprivate关键字来操纵它们。

If you are programming in C++ you should use classes. 如果您使用C ++编程,则应使用类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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