首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链表存储器

链表存储器
EN

Stack Overflow用户
提问于 2016-04-17 01:26:01
回答 2查看 53关注 0票数 0

当第一个对push的调用在下面的intersect中进行时,tail->next的值为NULL。我的理解是&tail->next将指向堆栈上的最后4个字节的虚拟对象,该对象持有指向next的指针。现在,当在push函数中更改head_ref时,不是要更改虚拟对象的下一个变量中存储的地址吗?因此,在我看来,虚拟总是指向列表的最后一个元素,尽管它在执行时正确地输出了列表的头。有人能解释一下每个推送电话的记忆中发生了什么吗?谢谢。

这个问题来自于这里

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-17 01:57:00

蠢货一开始是这样的:

代码语言:javascript
复制
______     ______
|dummy| -> |NULL|
| 0   |    |    |
-------    ------

在第一次调用push(&tail->next, a->data)之后,我将假设a->data5,它将考虑到这一点(请记住,tail此时指向dummy ):

代码语言:javascript
复制
 ______    _________      _____
|dummy| -> |new_node| -> |NULL|
|  0  |    |   5    |    |    |
 -----     ---------     ------

然后我们调用tail = tail->next;,这将导致tail指向new_node,这就是为什么当我们再次调用push(&tail->next, a->data)时,new_node号2会插入到旧的new_nodeNULL之间。

最后,我们调用return dummy->next,它将返回具有最近添加的节点的链接列表。虚拟本身将被删除,因为它是在堆栈上分配的。

如果我们这样编写push函数,它将变得更加清晰:

代码语言:javascript
复制
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;
}
票数 0
EN

Stack Overflow用户

发布于 2016-04-17 01:38:15

push的第一个调用确实改变了虚拟人的下一个指针,但是tail被高级到指向刚刚推送的元素(tail = tail->next)。所以下一个push操作在那个节点的next上,而不是虚拟的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36671706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档