Page 1 of 1

Lista inlantuita

Posted: 08 Sep 2017, 18:06
by stelian_2681
Urmatorul cod creează o listă simplă înlănţuită ale cărei noduri sunt structuri ce au următoarele câmpuri: firstName, secondName, CNP, eMail;
Nu inteleg de ce imi este afisat numai primul nod din cele trei.

Code: Select all

#include <iostream>
#include <cstring>
using namespace std;

struct Persons
{
    char *firstName;
    char *secondName;
    char *CNP;
    char *eMail;
};

class NODE
{
private:
    NODE *next;
public:
    Persons box;
    NODE(char firstName[], char secondName[], char CNP[], char eMail[])
    {
        box.firstName = new char[strlen(firstName)+1];
        strcpy(box.firstName, firstName);
        box.secondName = new char[strlen(secondName)+1];
        strcpy(box.secondName, secondName);
        box.CNP = new char[strlen(CNP)+1];
        strcpy(box.CNP, CNP);
        box.eMail = new char[strlen(eMail)+1];
        strcpy(box.eMail, eMail);
    }
    NODE* GetNext()
    {
        return next;
    }
    void SetNext(NODE *next)
    {
        this->next = next;
    }
};

class SinglyLinkedList
{
private:
    NODE *head;
public:
    SinglyLinkedList()
    {
        head = NULL;
    }
    bool isEmpty()
    {
        return head == NULL;
    }
    void AddNODE(NODE *newNode)
    {
        NODE *temp;
        if (isEmpty())
            head = temp = newNode;
        else
        {
            temp->SetNext(newNode);
            temp = newNode;
        }
        temp->SetNext(NULL);
    }
    void Print()
    {
        NODE *temp;
        temp = head;
        while (temp != NULL)
        {
            cout << "\n FirstName  : " << temp->box.firstName << endl;
            cout << " SecondName : " << temp->box.secondName << endl;
            cout << " CNP        : " << temp->box.CNP << endl;
            cout << " eMail      : " << temp->box.eMail << endl;
            temp = temp->GetNext();
        }
    }
};

int main()
{
    SinglyLinkedList obj;
    obj.AddNODE(new NODE("Dragu", "Stelian", "1911226284570", "dragu_stelian@yahoo.com"));
    obj.Print();
    obj.AddNODE(new NODE("Popescu", "Mircea", "1891226284462", "popescu.mircea@yahoo.com"));
    obj.Print();
    obj.AddNODE(new NODE("David", "Adrian", "1971226284462", "david_adrian@yahoo.com"));
    obj.Print();
    return 0;
}
Astept sugestii.

Re: Lista inlantuita

Posted: 08 Sep 2017, 20:50
by Viorel
Încearcă o altă funcție:

Code: Select all

void AddNODE( NODE *newNode )
{
	newNode->SetNext( head );
	head = newNode;
}
Și ar trebui să foloseși clasa special proiectată std::string.