gpt4 book ai didi

c++ - 使用模板插入函数丢失数字

转载 作者:行者123 更新时间:2023-11-28 02:55:40 25 4
gpt4 key购买 nike

大家好,我有个小问题。当我将数字插入到我的有序列表中时,除了我插入的最后一个数字之外,每个数字都会出现。我的计数变量显示,目前所有 6 个都在里面。但是当我打印列表时,最后一个不见了。任何帮助将不胜感激。时间至关重要,因为它在晚上 11:00 到期

有序列表的插入函数:

template <class T>
void OListType<T>::insert (const T& item) {
NodeType<T> *curr=this->head, *prev=NULL;
while (curr!=NULL && curr->item<item) {
prev = curr;
curr = curr->next;
}
if (prev==NULL) {
this->head = new NodeType<T>;
this->head->item=item;
this->head->next=curr;
}
else{
prev->next=new NodeType<T>;
prev->next->item=item;
prev->next->next=curr;
}
++this->count;
}

主程序:

#include <iostream>
#include "ListType.h"
#include "UListType.h"
#include "OListType.h"

using namespace std;

int main() {
OListType<int> OList_int;
UListType<int> UList_int;

OList_int.insert(45);
OList_int.insert(100);
OList_int.insert(7);
OList_int.insert(83);
OList_int.insert(29);
OList_int.insert(49);

cout<< "The Ordered List size after inserts: ";
cout<< OList_int.size() << endl << endl;

cout << "The Ordered List values after inserts: ";
cout << OList_int << endl << endl;

return 0;
}

Ostream 重载代码:

template <class U>
std::ostream &operator<< (std::ostream &out, const ListType<U> &list) {
if (!list.empty()) {
NodeType<U> *temp=list.head->next;
out << list.head->item;
temp=temp->next;
while(temp!=NULL) {
out << "," << temp->item;
temp=temp->next;
}
}
return out;
}

如果您需要更多代码,我会提供。

最佳答案

template <class U>
std::ostream &operator<< (std::ostream &out, const ListType<U> &list) {
if (list.head) {
NodeType<U> *temp=list.head;
out << list.head->item;
temp=temp->next;
while(temp!=NULL) {
out << "," << temp->item;
temp=temp->next;
}
}
return out;
}

对 NodeType *temp=list.head 进行了以下更改; :)

关于c++ - 使用模板插入函数丢失数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058644/

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