当第一个对push的调用在下面的intersect中进行时,tail->next的值为NULL。我的理解是&tail->next将指向堆栈上的最后4个字节的虚拟对象,该对象持有指向next的指针。现在,当在push函数中更改head_ref时,不是要更改虚拟对象的下一个变量中存储的地址吗?因此,在我看来,虚拟总是指向列表的最后一个元素,尽管它在执行时正确地输出了列表的头。有人能解释一下每个推送电话的记忆中发生了什么吗?谢谢。
这个问题来自于这里
struct node* sortedIntersect(struct node* a, struct node* b)
{
struct node dummy;
struct node* tail = &dummy;
dummy.next = NULL;
while (a != NULL && b != NULL)
{
if (a->data == b->data)
{
push((&tail->next), a->data);
tail = tail->next;
a = a->next;
b = b->next;
}
else if (a->data < b->data) /* advance the smaller list */
a = a->next;
else
b = b->next;
}
return(dummy.next);
}
void push(struct node** head_ref, int new_data)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}发布于 2016-04-17 01:57:00
蠢货一开始是这样的:
______ ______
|dummy| -> |NULL|
| 0 | | |
------- ------在第一次调用push(&tail->next, a->data)之后,我将假设a->data是5,它将考虑到这一点(请记住,tail此时指向dummy ):
______ _________ _____
|dummy| -> |new_node| -> |NULL|
| 0 | | 5 | | |
----- --------- ------然后我们调用tail = tail->next;,这将导致tail指向new_node,这就是为什么当我们再次调用push(&tail->next, a->data)时,new_node号2会插入到旧的new_node和NULL之间。
最后,我们调用return dummy->next,它将返回具有最近添加的节点的链接列表。虚拟本身将被删除,因为它是在堆栈上分配的。
如果我们这样编写push函数,它将变得更加清晰:
void push(struct node** head_ref, int new_data)
{
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
/* save old head */
struct node* old_head = *head_ref;
/* move the head to point to the new node */
*head_ref = new_node;
/* link the old list off the new node */
new_node->next = old_head;
}发布于 2016-04-17 01:38:15
对push的第一个调用确实改变了虚拟人的下一个指针,但是tail被高级到指向刚刚推送的元素(tail = tail->next)。所以下一个push操作在那个节点的next上,而不是虚拟的。
https://stackoverflow.com/questions/36671706
复制相似问题