What is the problem with my LinkedList class?

class LinkedList
{
  private:
    int data;  
    LinkedList *ptr;  
public:
  LinkedList(int i_data)  
  { 
    data = i_data;  
    ptr = 0;  
  }  
  ~LinkedList()  
  {  
    delete ptr ;  
  }  
  void insert(LinkedList *node)  
  {  
    while(this->ptr!= 0)  
    this = this->ptr;  

    this->ptr= node;  
  }  
}

I will create a head like node, head = new LinkedList(4)and then it will call as head->insert(new LinkedList(5))later. Could you tell me that the above class is a linked list. I think it has a node that contains the address of the next node. Please correct me if I am wrong

+3
source share
6 answers

Yes, this type, of course, is a structure with a special connection of lists, since it has a data slot and the following pointer.

One thing I would change is the method insert. IMHO, it is more convenient for this method to take the data type, in this case int, and let the class LinkedListtake on the task of isolating the data structure.

.

void insert(int data) {
    while(this->next != 0)  
    this = this->next;  

    this->next = new LinkedListNode(data);  
}
+2

node NULL,

void insert (LinkedList * node)
{
  while (this- > next!= 0)
  this = this- > next;

this->next = node; 
node->next = 0;

}

+1

, STL. , - .

this, insert - . . , , .

, , . , , , :

class List {
public:
  List();                   // creates an empty list

  void append( int value ); // adds a new element at the tail of the list
     // push_front( value ) in STL sequence containers

  void insert( int value ); // inserts a new element before the head of the list
     // push_back( value ) in STL sequence containers

  // some way of iterating (I like STL iterators,
  // but Java style iterator --even if worse-- could suffice)
};

, ( , , , , !). , LinkedList ( node), . append , . (!!)

, ( , X , , ...), , , :)

+1
  • . }; .
  • , , .
  • , node list, , .
0

'next' ?

() 'this- > next', '' ptr '.

0

, .
, NULL:

node head = new LinkedList (4)

  • , ( )
  • I will have a node class (internal) that contains data and a pointer to the next
  • I would update the interface to take a data object (as described in Jared Par).

the code:

class LinkedList
{
    struct Node
    {
         Node(int d): data(d) {next = NULL;}
        ~Node()               {delete next;}
        int                   data;
        Node*                 next;
    };

    std::auto_ptr<Node>   head;

    Insert(int data)
    {
        if (head.get() == NULL)
        {
            head.reset(new Node(data));
        }
        else
        {
            Node* loop;
            for(loop = head.get();loop->next != NULL;loop = loop->next) {};
            loop->next = new Node(data);
        }
    }
};

LinkedList   list;
0
source

Source: https://habr.com/ru/post/1737993/


All Articles