0

我正在尝试获得一个可以调用 insert_back 的工作函数,它将值插入到列表的末尾

到目前为止,我有代码,我想我已经被难住了。

    template <class Object>
void List<Object>::insert_back( const Object& data ) {
    ListNode<Object>* newnode = new ListNode<Object>( data, head->getNext() );
        if (!head) {

            head = newnode;
            return;
        }
        while (head->getNext()) {
            continue;
        }
        head->setNext( newnode );
    }

当我调用 insert_back 时,这不会返回任何内容并阻塞程序

.H 文件

#ifndef LIST_H
#define LIST_H
#include <iostream>
#include "ListNode.h"
#include "ListIterator.h"

namespace cs20 {

template <class Object>
class List {
    public:
    List();
    List( const List& rhs );
    ~List();

    bool isEmpty() const;
    bool isIncreasing() const;
    void makeEmpty();
    ListIterator<Object> zeroth() const;
    ListIterator<Object> first() const;
    void insert( const Object& data,
                 const ListIterator<Object> &iter );
    void insert( const Object& data );
    void insert_back( const Object& data );
    ListIterator<Object> findPrevious( const Object& data ) const;
    void remove( const Object& data );

    const List& operator =( const List& rhs );
    const List& operator <<( const List& rhs );
private:
    ListNode<Object> * head;

};

}
#endif
4

3 回答 3

3

将您的代码更改为:

ListNode<Object>* lastNode = head;
while (lastNode->getNext())
    lastNode = lastNode->getNext();
lastNode->setNext( newnode );
于 2013-10-22T00:53:37.977 回答
1

This looks suspicious:

ListNode<Object>* newnode = new ListNode<Object>( data, head->getNext() );

You are passing head->getNext() into your new node. I assume that parameter initialises the next-pointer in the new list node. You should surely pass NULL rather than the second element of the list.

The other problem is that you modify head inside insert_back. The head variable is a member of your class. If you move the head all the way to the end of your list, you will lose your list. Use a temporary variable to iterate instead.

于 2013-10-22T00:54:06.713 回答
0

除非您真的完全不关心性能,否则您可能希望在ListNode<Object> *tail;您的List课程中添加一个。让它指向列表中的最后一个节点。当您需要添加新节点时,在它指向的节点之后立即添加新节点,并更新它以指向您刚刚添加的新节点。

于 2013-10-22T02:26:17.767 回答