0

こんにちは皆さん 私は C++ でクラスを使用して LinkedList の実装を行っています。これまでのところ、ノード クラスと add メソッドのみを実行しました。たとえば、新しい要素を追加し、最初のポインターを確認すると、追加した最後の要素を指しています...

ノード クラス:

template<class T>
class Node
{
private:
    T element;
public:
    Node<T> *next;

    Node( T e ){
        element = e;
        next = NULL;
    }

    friend ostream& operator<<(ostream& os, const Node<T>& nd)
    {
        os << nd.element;
        return os;
    }   

};

そして LinkedList クラス:

 template<class T>
 class LinkedList{

    private:
        int size;

    public: 
        Node<T> *first;
        Node<T> *last;          

        LinkedList(){
            first = NULL;
            last = NULL;
            size = 0;
        }

        void add( T element ){
            Node<T> n (element);

            if( size == 0 ){
                first = &n;
            }else{
                last->next = &n;
            }
            last = &n;
            size++;     
        }

        int getSize(){
            return size;
        }


   };

たとえば、私は主に次のことを行います。

LinkedList<int> list;

list.add(5);
list.add(7);


cout << *list.first;

そして、最初の要素として「7」を示しています...

前もって感謝します。

4

1 に答える 1

5

You can't do this. By "this", I mean storing a pointer to a locally scoped Node instance, and expecting that object to persist outside of its original scope:

    void add( T element ){
        Node<T> n (element);     // This will only exist for the function's duration

        if( size == 0 ){
            first = &n;          // <-- naughty
        }else{
            last->next = &n;     // <-- naughty
        }
        last = &n;               // <-- naughty
        size++;     
    }

As you can see, you've been very naughty. Once the function exits, that node is deleted. Actually, it only existed on the stack, so it just kinda vanishes. As luck would have it, when you call the function again, you just happen to get the same stack address back so it looks like your first node has changed.

So what do you do? Allocate on the heap:

    void add( T element ){
        Node<T> *n = new Node<T>(element);

        if( size == 0 ){
            first = n;
        }else{
            last->next = n;
        }
        last = n;
        size++;     
    }

This is no longer naughty, and you can continue to make other pointer-related mistakes that are the basic rites of passage of a C or C++ programmer. =)

Make sure that when you are finished with your linked list, you crawl over it and delete each node to release the memory that you allocated.

于 2013-07-09T03:29:28.807 に答える