c - 在 C 中打印不需要的空行

标签 c linked-list printf

我正在用 C 编写一个程序,将字符串转换为链接列表并更改它们。

出于某种原因,在我调用反向函数,然后打印列表后,它会在打印反向列表之前打印一个新行。

例如,假设我的“列表”包含... a->p->p->l->e->NULL

在 main() 中,如果我调用... print(list);打印(列表);

我的输出:

apple
apple

但是,在 main() 中,如果我调用... print(list);列表=反向(列表);打印(列表);

我的输出:

apple 
/*empty line*/ 
elppa

这是我的 rev()

node *rev(node *head){

    node *r_head = NULL;
    while (head) {
        node *next = head->next;
        head->next = rev_head;
        r_head = head;
        head = next;
    }

    return r_head;
}

最佳答案

你似乎把列表颠倒得太好了;列表末尾的 NULL 正在成为新的头部,这会创建您所关心的空白空间。

要修复此问题,我建议检查 while 循环内的 head->next 是否为 NULL:

node *rev(node *head){

    node *r_head = NULL;
    while (head->next) {
        node *next = head->next;
        head->next = rev_head;
        r_head = head;
        head = next;
    }
    r_head = head;

    return r_head;
}

此代码尚未经过测试,但我相信它应该可以工作。

关于c - 在 C 中打印不需要的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22750482/

相关文章:

c++ - 使用结构模板的结构模板

haskell - 为什么 Haskell 要求对 printf 的数字进行消歧,而不是对 show 进行消歧?

c - 在 freebsd 中,如何知道编译期间内核中启用了哪些选项

c++ - 执行此代码时,不显示任何输出。这是为什么?

java - 优先级队列(从头开始)和链表

c - typedef 结构清晰度

c - 在 C 奇怪的输出中写入和读取 CSV 文件

c - 斯普林特夫 : pad with '\0' character instead of space

c - 我的函数一直返回 0 而不是实际计算的返回值?

.net - P/Invoke 和非托管 DLL 状态