插入链表的后面

Insert in back of Linked List

本文关键字:链表 插入      更新时间:2023-10-16

我正在尝试获取一个可以调用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

将代码更改为:

ListNode<Object>* lastNode = head;
while (lastNode->getNext())
    lastNode = lastNode->getNext();
lastNode->setNext( newnode );

看起来很可疑:

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

您正在将head->getNext()传递到新节点中。 我假设该参数初始化新列表节点中的下一个指针。 您肯定应该传递NULL而不是列表的第二个元素。

另一个问题是您在insert_back内部修改headhead变量是类的成员。 如果你把头一直移到列表的末尾,你将失去你的列表。 改用临时变量进行迭代。

除非你真的根本不关心性能,否则你可能想在你的List类中添加一个ListNode<Object> *tail;。 保持它指向列表中的最后一个节点。当您需要添加新节点时,请紧跟在它指向的节点之后添加新节点,并将其更新为指向刚刚添加的新节点。