【问题标题】:What is the role of the Node ** list double pointer in the enqueue function for queues using linked list?Node ** list双指针在使用链表的队列的enqueue函数中的作用是什么?
【发布时间】:2022-11-17 00:32:41
【问题描述】:

我被要求使用没有头节点的链表来实现队列。我的老师给了我们这个 sn-p 来引用入队功能。我熟悉如何使用队列操作。但是当双指针与函数一起使用时,我总是感到困惑。在大多数情况下,我不确定双指针指向哪个变量。我想知道 Node ** list 是什么意思。

任何帮助或解释表示赞赏

这是我提到的 sn-p

void insertNode(Node * prev,int x) {
    Node * new = (Node *) malloc(sizeof(Node));
    new->val = x;
    new->next = prev->next;
    prev->next = new;
}

void enqueue(Node ** list, int x) {
    Node * new = (Node *) malloc(sizeof(Node));
    if (isEmpty(*list)) {
        *list = new;
        (*list)->val = x;
        (*list)->next = NULL;
    }
    else {
        new = *list;
        while (new->next != NULL) 
            new = new->next;
        insertNode(new,x);
    }
}

【问题讨论】:

  • 模拟通过引用传递.
  • @Someprogrammerdude 这是我第一次在这个方向上读到它。我听说过另一个方向,人们多次将引用传递称为指针的模拟!
  • 同意,指针是真正的交易,而引用只是试图隐藏实际指针以使其更具可读性,不幸的是在此过程中失去了一些功能。

标签: c pointers data-structures queue singly-linked-list


【解决方案1】:

通常双指针作为函数的参数用于修饰指针本身。

例子:

int a = 5;
int b = 10;

void foo(int *x)
{
    x = &b;
}

void bar(int **x)
{
    *x = &b;
}


int main(void)
{
    int *ptr = &a;

    foo(ptr);
    printf("%d
", *ptr);

    bar(&ptr);
    printf("%d
", *ptr);
}

输出:

5
10

函数bar修改指针ptr。 函数foo 不是,因为 x 是具有函数作用域的局部变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2021-06-29
    • 1970-01-01
    • 2011-11-08
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多