c++ - 如何正确地将指针传递给函数?
问题描述
我不知道标题是否适合这个问题,但我认为我的问题是关于我如何在函数中正确传递指针。所以我有一个由头部指向的链表;
假设我有这个由 head 指向的链表:{1, 2, 3, 4, 5, NULL} 我调用函数 NextNode(head),然后给出列表,结果将是 head 指向 2 . 我希望下一次,我调用该函数,我应该有指向 3 的结果。等等。我希望当调用该函数时,下一个节点不应该总是 head->next,但应该继续。
我有一个以头部为参数的函数;
struct node
{
int val;
node*next;
}
node * create()
{
node*tmp;
node *head;
for (int i = 1; i<6; i = i + 1)
{
tmp = new node;
tmp->val = i;
tmp->next = head;
head = tmp;
}
return head;
}
node* NextNode(node*current)
{
if (somethingHappens)
{
current = current->next; //this is wrong. Because it's important to not lose the pointer of head;
}
return current;
}
int main()
{
node* result;
node* another;
node* head;
head = create();
result = NextNode(head);
std::cout << result->val << std::endl;
//I call again the function, giving always as paramter the head pointer
another = NextNode(head);
std::cout << another->val << std::endl;
return 0;
}
所以 result->val 应该给出 2 作为结果,而 another->val 应该给出 3。但显然这不会发生,因为 head 是固定的。还有其他方法可以做到这一点吗?该代码是我想做的伪代码。希望我已经清楚了,英语不是我的第一语言,所以请耐心等待。
解决方案
更改another = NextNode(head);
为another = NextNode(result);
。下次调用时,您不会传递从先前调用中获得的下一个节点NextNode()
。
(附带说明,我看到您发布的代码不是工作代码,或者某些代码丢失且未发布;但代码足以理解您的疑问并找出解决方案。)
推荐阅读
- android - Android 屏幕阅读器在定位颤振抽屉时显示“关闭”
- excel - 提供列内的总和,移动到同一行列上的下一个标题名称,复制粘贴
- excel - Excel 公式中空格/空白字符 (" ") 的长度
- css - React - 输入上的伪元素根本没有呈现
- python - 检查目标时出错:预期 dense_24 有 3 个维度,但得到了形状为 (3283, 1) 的数组
- vue.js - vue访问图片
- ios - MongoSwift Pod 包含 100 个编译器错误。安装后无法构建
- javascript - WebGL,gl 矩阵。如何从相机视图和投影矩阵中获取截锥体顶点?
- javascript - 选择时间后我不确定
- dart - 如何在字符串中按此名称获取属性?