gpt4 book ai didi

c++ - 在 SLL 中查找负值

转载 作者:行者123 更新时间:2023-11-28 05:03:21 26 4
gpt4 key购买 nike

要求我遍历一个单向链表,找到负节点,删除它们并返回删除节点的数量。

这是我目前的代码,但我总是从函数返回 counter=1

是for循环和if语句有什么问题,还是别的什么

bool IntSLList::DeleteNegativeNodes()
{
int counter=0;
if(IsEmpty() == true)
counter++;

if(head->val<0)
{
DeleteFromHead();
counter++;
}

if(tail->val<0)
{
DeleteFromTail();
counter++;
}


IntSLLNode *node, *pred, *tmp;
node = pred = NULL;


for(pred = head, node = head->next;
node != NULL;
node = node->next, pred = pred->next)
{
if(node->val<0)
{
node->flag = 1;

}
}
for(tmp = head; tmp != NULL; tmp = tmp->next)
{
if(tmp->flag==1)
counter++;
delete tmp;


}
return counter;
}

int main()
{
int n,x,z;
IntSLList list1;


cout <<"Insert number of nodes u'd like inserted in list" << endl;
cin >> n;

for(int i=0;i<n;i++)
{
cin >> x;
list1.AddToTail(x);
}
z=list1.DeleteNegativeNodes();

cout << "Number of negative deletes nodes is : " << z << endl;

}

最佳答案

问题出在返回值的类型上。检查方法的签名:

bool IntSLList::DeleteNegativeNodes()

那里的返回类型是bool。当您从您的方法返回 int 类型的 counter 时,它是 implicitly convertedbool。零值变为 false。所有其他值变为 true

调用方:

z=list1.DeleteNegativeNodes();   

bool 值隐式转换为 int。因此你得到 1

DeleteNegativeNodes 的返回类型更改为 int 以修复问题。

关于c++ - 在 SLL 中查找负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45403474/

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