Связные списки в с++

399
06 января 2018, 03:14

Очень сложно разобраться со связными списками( Помогите разобраться в этой части кода,пожалуйста:

class node
{
public:
    int data;   // data
    node *next;  // pointer
    node(int x)
    {
        data = x;
        next = NULL;
    }
};
class LinkedList
{
public:
    node *head;
    //function to add node at front
    void addAtFront(node *n)
    {
        n->next = head;
        head = n;
    }

И в этой:

    node *n1 = new node(1);
    node *n2 = new node(2);
    node *n3 = new node(3);

Код полностью:

class node
{
public:
    int data;   // data
    node *next;  // pointer
    node(int x)
    {
        data = x;
        next = NULL;
    }
};
class LinkedList
{
public:
    node *head;
    //function to add node at front
    void addAtFront(node *n)
    {
        n->next = head;
        head = n;
    }
    //function to check whether the list is empty
    bool isEmpty()
    {
        if (head == NULL) { return 1; }
        else { return 0; }
    }
    //function to add node at the end
    void addAtEnd(node *n)
    {
        if (head == NULL)
        {
            head = n;
            n->next = NULL;
        }
        else
        {
            node *n2 = getLastNode();
            n2->next = n;
        }
    }
    //function to get the last node
    node* getLastNode()
    {
        node* ptr = head;
        while (ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        return ptr;
    }
    //function to search a value
    node* search(int k)
    {
        node *ptr = head;
        while (ptr != NULL && ptr->data != k)
        {
            ptr = ptr->next;
        }
        return ptr;
    }
    //function to delete any node
    node* deleteNode(int x)
    {
        node *n = search(x);
        node *ptr = head;
        if (ptr == n)
        {
            ptr->next = n->next;
            return n;
        }
        else
        {
            while (ptr->next != n)
            {
                ptr = ptr->next;
            }
            ptr->next = n->next;
            return n;
        }
    }
    //function to print the list nodes
    void printList()
    {
        node *ptr = head;
        while (ptr != NULL)
        {
            cout << ptr->data << " -> ";
            ptr = ptr->next;
        }
    }
    LinkedList()
    {
        head = NULL;
    }
};
int main()
{
    LinkedList L;
    node *n1 = new node(1);
    node *n2 = new node(2);
    node *n3 = new node(3);
    L.addAtFront(n1);
    L.addAtFront(n2);
    L.addAtEnd(n3);
    L.printList();
    delete n1;
    delete n2;
    delete n3;
    system("pause");
    return 0;
}
Answer 1
class LinkedList
{
    // инкапсулируйте данные // пользователью они не нужны
    struct Node  // для читабельности имя класса начинайте с большой буквы
    {
        int data;  
        Node *next; 
        Node(int x) : data(x), next(0) {} // лучше инициализировать так    
    };
    Node *head;
public:
    LinkedList() : head(0) {}
    // в список добавляется не узель, а значение а после 
    // функция пусть возвращает  bool для того, чтоб в любой момент
    // могли узнать, добавился ли новый узель?...
    bool addAtFront(int i)
    {
        // Создаем новый узел для значения
        // Не забудем проверить, что память удалось выделить
        if( Node* node = new Node(i) ) {
            // Новый узел привязывается к старому головному элементу
            node->next = head;            
            // Новый узел сам становится головным элементом
            return  head = node;
        }
         return false; // не удалось
    }
    // смысль структуры Node хранить int и иметь связь со следующей структурой
};
int main()
{  
    LinkedList list;
    list.addAtFront(1);
    list.addAtFront(2);
    list.addAtFront(3);
    // и т. д.
    return 0;
}
READ ALSO
Содержимое указателя

Содержимое указателя

Немного запутался:

277
Поиск максимальной суммы в подмассиве

Поиск максимальной суммы в подмассиве

Дан массив, требуется найти такой подмассив с максимальной суммой элементов в нем, чтобы начало и конец отрезка были одинаковыми(вывести...

316