C: 如何倒序打印列表?

C: how to print a list in reverse order?

我正在尝试以相反的顺序打印 tree_nodes 的列表:

当前提示示例:/helloFellow/hello/root / >

想要的结果:root/hello/helloFellow / >

有什么方法可以有效地做到这一点?

// *prints the prompt (e.g. /bar/baz/ >) in every iteration of the main loop
// *show all directories on the path in correct order
void show_prompt(struct tree_node *cwd) {
    struct tree_node *parDir = cwd->parent;
    struct tree_node *originalDir = cwd;

    while (cwd->parent != NULL) {
        printf("/");
        printf("%s", cwd->parent->string_buffer);
        cwd = cwd->parent;
    }
    cwd = originalDir;
    printf("/ >");
}

你可以使用递归:

void print_path( struct tree_node * cwd ) {
    if ( cwd->parent != NULL )
        print_path( cwd->parent );
    printf( "%s/", cwd->string_buffer );
}

正如 Kenney 所指出的,您可以使用递归。另一种解决方案是修改您的链接列表以包含双向指针,即指向列表中的上一个和下一个元素。然后你还保留指向列表头部和尾部的指针。您可以使用两个结构封装它,例如:

struct ListNode {
    struct ListNode *prev;
    struct ListNode *tail;
};

struct LinkedList {
    struct ListNode *head;
    struct ListNode *tail;
};

这样做的优点是可以很容易地完成此操作(以及其他操作,如在尾部插入)。不利的一面是,您还需要为每个节点提供更多内存并跟踪更多指针。

顺便说一句,既然你要求高效,一般来说递归比普通循环实现更昂贵,因为每个递归调用都需要在堆栈中为函数创建一个新帧等。这并不是说您不应该使用它。递归解决方案非常优雅,有时比其他替代方案更好,即 efficient/easier。此外,在许多情况下,编译器对它们进行了很好的优化!