Связанный список (недопустимое преобразование из 'Node <int>*' в 'int' [-fpermissive] |) - PullRequest
3 голосов
/ 09 июля 2019

Я хочу создать Node like Arraylist в c ++. Когда я создаю метод get (); это говорит об ошибке. Я не понимаю, когда я иду, чтобы найти ответ в Интернете. Можете ли вы помочь мне найти этот ответ?

template<typename T>

struct Node{           //Node
    T data;
    Node<T> *next;
    Node(){
       next=NULL;
    }
    Node(T value){
        data=value;
        next=NULL;
    }

};

template<typename T>

class LinkedList{   //class Node 
    public:
        Node<T> *head;
        Node<T> *tail;

        void add(T value){         //method create newnode add to tail
            Node<T> *newNode=new Node<T>(value);
            if (head == NULL){
                head=newNode;
                tail=newNode;
            }
            else {
                tail->next=newNode;
                tail=newNode;
            }
        }
        void PrintAll(string Name){   //method print all node
            Node<T> *current;
            int i=0;
            current=head;
            while (current != NULL ){
                printf("%s[%d]=%d\n",Name.c_str(),i,current->data);
                current=current->next;
                i++;
            }
        }
        T get(int index){      //method show node in parameter 
            Node <T> *current=head;
            int count=0;
            while (current != NULL){
                if ( count == index) return current->next;
                current=current->next;
                count++;
            }
        }

};

ошибка: недопустимое преобразование из 'Node *' в 'int' [-fpermissive] | предупреждение: управление достигает конца не пустой функции [-Wreturn-type] |

Ответы [ 2 ]

2 голосов
/ 09 июля 2019

Внутри get() вы возвращаете Node* вместо T, внутри if, если быть точным.Вам, вероятно, следует сделать следующее:

    T get(int index){      //method show node in parameter 
        Node <T> *current=head;
        int count=0;
        while (current != NULL){
            if ( count == index) return current->data;
            current=current->next;
            count++;
        }
    }

Вам следует также обработать случай, когда индекс недопустим, в этих случаях можно сгенерировать исключение.

0 голосов
/ 09 июля 2019

Структура Node должна быть определена в классе LinkedList и быть частным членом класса.

Функция-член PrintAll должна быть объявлена ​​с квалификатором const (иимя функции должно начинаться со строчной буквы).

Функция get должна выдавать исключение в случае, если список содержит меньше данных, чем указанный индекс.В противном случае он должен вернуть значение элемента данных data найденного узла.

Вот демонстрационная программа, которая показывает, как можно определить список.

#include <iostream>
#include <string>
#include <stdexcept>

template<typename T>
class LinkedList
{
private:
    struct Node
    {
        T data;
        Node *next;

        Node() : data( T() ), next( nullptr )
        {
        }

        Node( const T &value ) : data( value ), next( nullptr )
        {
        }
    };

    Node *head = nullptr;
    Node *tail = nullptr;

public:
    void add( const T &value )
    {
        Node *newNode = new Node( value );
        if ( head == nullptr )
        {
            head = tail = newNode;
        }
        else 
        {
            tail = tail->next = newNode;
        }
    }

    void printAll( const std::string &name = "" ) const 
    {
        size_t i = 0;

        for ( auto current = head; current != nullptr; current = current->next )
        {
            std::cout << name << i++ << ": " << current->data << '\n';
        }
    }

    T get( size_t index ) const noexcept( false )
    {
        auto current = head;

        while ( index != 0 && current != nullptr ) 
        {
            current = current->next;
            --index;
        }

        if ( current == nullptr ) throw std::out_of_range( "Too big index" );
        else return current->data;
    }
};

int main()
{
    LinkedList<int> list;

    list.add( 1 );
    list.add( 2 );
    list.add( 3 );

    list.printAll();

    try
    {
        for ( size_t pos = 0; ; ++pos )
        {
            auto value = list.get( pos );

            std::cout << "At position " << pos << " there is stored " << value << '\n';
        }            
    }
    catch ( const std::exception &ex )
    {
        std::cout << ex.what() << '\n';
    }
}

Вывод программыis

0: 1
1: 2
2: 3
At position 0 there is stored 1
At position 1 there is stored 2
At position 2 there is stored 3
Too big index

Конечно, вы должны добавить определение списка с деструктором, конструктором копирования и оператором назначения копирования.В этом случае вам также нужно явно определить конструктор по умолчанию.

...