gpt4 book ai didi

c++ - 在链表后面插入

转载 作者:行者123 更新时间:2023-11-27 23:12:16 24 4
gpt4 key购买 nike

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

关于c++ - 在链表后面插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19507228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com