我可以仅使用 head 指针直接遍历此链表吗?

Can I directly traverse this linked list using just the head pointer?

提问人:itzmartin_20 提问时间:6/20/2023 最后编辑:Vlad from Moscowitzmartin_20 更新时间:6/21/2023 访问量:54

问:

我最近刚开始DSA,这个问题可能看起来微不足道,但非常感谢那些认真对待它的人。这是我的程序:

#include<stdio.h>
#include<stdlib.h>

struct node{
    int data;
    struct node *link;
};

typedef struct node node;
    
void printNodes(node* head) {
    if(head == NULL)
        printf("Linked list is empty");
    node *ptr = head;
    while(ptr != NULL) {
        printf("%d ", ptr->data);
        ptr = ptr->link;
    }
}

int main() {
    node *head = NULL;
    head = malloc(sizeof(node));
    head->data = 3;
    head->link = NULL;

    node *current = NULL;
    current = malloc(sizeof(node));
    current->data = 4;
    current->link = NULL;
    head->link = current;
        
    current = malloc(sizeof(node));
    current->data = 5;
    current->link = NULL;
    head->link->link = current;
    
    printNodes(head);
}

我有以下函数来遍历和打印链表中节点的数据

void printNodes(node *head) {
    if(head == NULL)
        printf("Linked list is empty");
    node *ptr = NULL;
    ptr = head;
    while(ptr != NULL){
        printf("%d ", ptr->data);
        ptr = ptr->link;
    }
}

我认为如果我们不使用,代码就可以正常工作:node* ptr

void printNodes(node *head) {
    if(head == NULL)
        printf("Linked list is empty");
    while(head != NULL){
        printf("%d ", head->data);
        head = head->link;
    }
}

请告诉我我的想法是否有任何问题。

c 函数 数据结构 链接列表 按值传递

评论

1赞 trincot 6/20/2023
这里没有问题。请:(1)指定问题到底是什么(2)如何重现该问题 - 提供调用此函数的代码 (3)如何使用调试器来分析问题(4)使用您正在使用的编程语言标记问题。

答:

0赞 Vlad from Moscow 6/21/2023 #1

由于指向列表第一个节点的指针按值传递给函数,即该函数处理指针值的副本,因此该函数无法更改在 main 中声明的原始指针。headheadhead

在这种情况下,指针可能会从函数定义中删除。ptr

请注意,由于该函数不会更改列表本身,因此应使用限定符声明其参数,例如const

void printNodes( const node *head )
{
    if ( head == NULL )
    {
        printf("Linked list is empty");
    }
    else
    {
        while ( head != NULL )
        {
            printf("%d ", head->data);
            head = head->link;
        }
    }
}