首页 > 解决方案 > 如何正确地将指针传递给函数?

问题描述

我不知道标题是否适合这个问题,但我认为我的问题是关于我如何在函数中正确传递指针。所以我有一个由头部指向的链表;

假设我有这个由 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 是固定的。还有其他方法可以做到这一点吗?该代码是我想做的伪代码。希望我已经清楚了,英语不是我的第一语言,所以请耐心等待。

标签: c++pointers

解决方案


更改another = NextNode(head);another = NextNode(result);。下次调用时,您不会传递从先前调用中获得的下一个节点NextNode()

附带说明,我看到您发布的代码不是工作代码,或者某些代码丢失且未发布;但代码足以理解您的疑问并找出解决方案。


推荐阅读