【问题标题】:function, linked list. copying one linked list to another函数,链表。将一个链表复制到另一个链表
【发布时间】:2014-02-21 15:22:08
【问题描述】:

我写了这个函数:

void something(struct node* head1, struct node* head2)
{
    statement 1 .......
    statement 2 .......
    so on.........
    // Want to make list2 (head1) be the same as list1 (head1):
    head2=head1
}

但这不会改变head2。它在函数中执行,但一旦返回主程序就没有,为什么?

【问题讨论】:

  • 你是怎么调用“某事”函数的?
  • 如果您用所用语言标记您的问题,您将获得更好的答复。仅从代码示例看起来像 C。
  • 如果这是 C:您不能分配实际值并期望它们会改变。您可以更改指向的值。因此,您无法更改指针head1head2,但您可以更改它们指向的结构。
  • 请发布更多代码,例如node 结构。如果不知道您打算让这个 sn-p 实际做什么,我们无法给出完整的答案。

标签: c linked-list


【解决方案1】:

您似乎希望 head1 和 head2 都指向同一个链表,您的代码的问题是您将参数作为按值调用传递,这就是为什么它没有反映您需要传递参数的函数的原因通过指针调用(参考)。 试试这个方法

struct Node
{
int info;
Node *next;   
}

main{
Node * head1,*head2;

// call like this

something(&head1,&head2);

}

something(Node **temphead1, Node **temphead2){

//here you can use 

//(*temphead1)

//and 

//(*temphead2)

//to perform operation 

//for example you can display list item

while((*temphead1)!=null){

printf("%d",(*temphead1)->info);

(*temphead1)=(*temphead1)->next;
}

while((*temphead2)!=null){

printf("%d",(*temphead2)->info);

(*temphead2)=(*temphead2)->next;

}
// below line will do what you were looking for

(*temphead2)=(*temphead1);

// now you can check head1 =head2 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多