需要帮助,需要计算链表中负值的数量,C++
Need help, need to count the number of negative values inside a linked list, C++
所以我正在完成在线课程的作业,我需要一些帮助来编程一种方法来计算C++中链表中负值的数量。
这是我现在拥有的代码以及我尝试过的一个awnsers:
#include <iostream>
#include <cstdlib>
using namespace std;
class IntNode {
public:
IntNode(int dataInit = 0, IntNode* nextLoc = nullptr);
void InsertAfter(IntNode* nodePtr);
IntNode* GetNext();
int GetDataVal();
private:
int dataVal;
IntNode* nextNodePtr;
};
// Constructor
IntNode::IntNode(int dataInit, IntNode* nextLoc) {
this->dataVal = dataInit;
this->nextNodePtr = nextLoc;
return;
}
/* Insert node after this node.
* Before: this -- next
* After: this -- node -- next
*/
void IntNode::InsertAfter(IntNode* nodeLoc) {
IntNode* tmpNext = nullptr;
tmpNext = this->nextNodePtr; // Remember next
this->nextNodePtr = nodeLoc; // this -- node -- ?
nodeLoc->nextNodePtr = tmpNext; // this -- node -- next
return;
}
// Grab location pointed by nextNodePtr
IntNode* IntNode::GetNext() {
return this->nextNodePtr;
}
int IntNode::GetDataVal() {
return this->dataVal;
}
int main() {
IntNode* headObj = nullptr; // Create intNode objects
IntNode* currObj = nullptr;
IntNode* lastObj = nullptr;
int i = 0;
int negativeCntr = 0;
headObj = new IntNode(-1); // Front of nodes list
lastObj = headObj;
for (i = 0; i < 10; ++i) { // Append 10 rand nums
currObj = new IntNode((rand() % 21) - 10);
lastObj->InsertAfter(currObj); // Append curr
lastObj = currObj; // Curr is the new last item
}
currObj = headObj; // Print the list
while (currObj != nullptr) {
cout << currObj->GetDataVal() << ", ";
currObj = currObj->GetNext();
}
cout << endl;
currObj = headObj; // Count number of negative numbers
while (currObj != nullptr) {
/* Your solution goes here */
if (currObj > 0)
{
negativeCntr++;
}
currObj = currObj->GetNext();
}
cout << "Number of negatives: " << negativeCntr << endl;
return 0;
}
我不确定在这种情况下使用什么语法,我在书中徘徊寻找一些解决方案,但找不到任何东西。
这似乎是最简单的方法。
if(currObj->GetDataVal() < 0) negativeCntr++;
相关文章:
- 需要帮助设置在C++中使用的Potrace
- 在指针的帮助下,文本文件中单词的频率
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 如何在Qbutton的帮助下更改Q对话框的宽度
- 需要帮助将结构数组传递给函数
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 有人可以帮助我处理正则表达式吗?
- C++调用具有 *this 属性的单个帮助程序函数
- C++:需要帮助了解运算符重载错误
- 需要以下代码的帮助,下面的代码有什么问题
- CS1 项目帮助C++
- 用于检查值是否为其任何参数的帮助程序函数
- 需要有关此 if 语句的帮助
- 类型限定宏帮助程序
- CoreCLR 中的检测探查器 - 将帮助程序程序集加载到 dotnet 进程的方法
- NS3 插槽混淆(需要帮助理解)
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 需要帮助查找内存泄漏
- 有人可以帮助我理解这些参数/参数吗?