我需要遍历一个单链表,找到负节点,删除它们,并返回删除节点的数量。
这就是我到目前为止拥有的代码,但我总是从函数返回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;
}发布于 2017-07-31 03:42:19
问题出在返回值的类型上。检查方法的签名:
bool IntSLList::DeleteNegativeNodes()返回类型是bool。当您从您的方法返回int类型的counter时,它是implicitly converted to bool。零值变为false。所有其他值都将变为true。
在调用方方面:
z=list1.DeleteNegativeNodes(); bool值隐式转换为int。正因为如此,你得到了1。
将DeleteNegativeNodes的返回类型更改为int以修复此问题。
发布于 2017-07-31 03:05:57
在第二个中,你有
if(tmp->flag==1)我认为你必须使用
if(node->flag==1)https://stackoverflow.com/questions/45403474
复制相似问题