c - 打印链表的不同函数

标签 c linked-list

我看到了打印链表的函数的两个(不同?)实现。让我先给出我的代码示例:

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

struct node {
        int x;
        struct node *next;
};

void free_list(struct node *current);
void print_list_a(struct node *current);
void print_list_b(struct node *head);

int main()
{
        struct node *head;
        struct node *second;
        struct node *third;
        head = NULL;
        second = NULL;
        third = NULL;

        head = malloc(sizeof(struct node));
        if (!head) {
                exit(EXIT_FAILURE);
        }
        second = malloc(sizeof(struct node));
        if (!second) {
                exit(EXIT_FAILURE);
        }
        third = malloc(sizeof(struct node));
        if (!third) {
                exit(EXIT_FAILURE);
        }

        head->x = 1;
        head->next = second;

        second->x = 2;
        second->next = third;

        third->x = 3;
        third->next = NULL;

        print_list_a(head);
        print_list_b(head);

        free_list(head);

        exit(EXIT_SUCCESS);
}

上面我声明了两个打印函数 print_list_a()print_list_b()。他们的定义如下所示:

void print_list_a(struct node *current)
{
        while (current != NULL) {
                printf("%d->", current->x);
                current = current->next;
        }
}

void print_list_b(struct node *head)
{
        struct node *current;

        current = head;
        while (current != NULL) {
                printf("%d->", current->x);
                current = current->next;
        }
{

我的问题是:a) print_list_a()print_list_b() 之间有什么真正的区别吗?和 b) 是否有一个比另一个更受欢迎的优势?我有点困惑,因为两者都达到了同样的效果。 print_list_b() 的唯一优点是 head 出现在函数参数列表中。

最佳答案

功能之间没有区别。两者都使用一个局部变量来存储列表中的当前节点。考虑到函数参数也是函数的局部变量。

不过对于我来说,我更喜欢下面的函数定义

void print_list_b( const struct node *head )
{
    for ( const struct node *current = head; current != NULL; current = current->next )
    {
        printf( "%d->", current->x );
    }
}

或以下内容

void print_list_b( const struct node *current )
{
    for ( ; current != NULL; current = current->next )
    {
        printf( "%d->", current->x );
    }
}

但我会使用 for 循环。:)

考虑到编译器可以为所有循环生成相同的目标代码:while 或 for.:)

我建议您再考虑一个 print_list 函数。:)

void print_list( const struct node *current )
{
    if ( current != NULL )
    {
        printf( "%d->", current->x ); print_list( current->next );
    }
}

void print_list( const struct node *current )
{
    if ( current != NULL )
    {
        print_list( current->next ); printf( "%d->", current->x ); 
    }
}

关于c - 打印链表的不同函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30606012/

相关文章:

.net - LinkedList 中的 Foreach Item 是否按顺序给出项目?

c++ - 执行 CUDA 程序时出现段错误

C 数组和指针,当我给数组提供新地址时会发生什么?

c++ - 声明 float ***c 的含义

java - 帮助了解 Java 中的后向递归和 LinkedList

c++ - std::vector 与 std::list 与 std::slist 的相对性能?

c - 具有这种形式的链表/指针 list[0]

c++ - 使用模板将堆栈实现为链表时出现 "symbols not found"错误

c - 何时使用 GBaseInitFunc

c - 生成 RTE_Components.h