c - 在C中反转链表,代码麻烦

标签 c macos

我尝试在 c 中反转一个简单的链表(包含 0、1、2、3...9),但我的代码无法完全运行。关于我做错了什么有什么想法吗?

我很确定我的反向函数是正确的,我遇到的主要问题是弄清楚将什么放入反向()函数的参数中。这个程序非常接近运行,它可以编译,但不会打印反向列表,所以我不确定我做错了什么。有人可以提供的任何帮助将不胜感激! :)

代码:

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

struct node;
typedef struct node Node;

struct node
{
    int data;
    Node* next;
};

void reverse(Node* *);

int main(int argc, char* argv[])
{
    Node* head = NULL;
    int i;
    Node* temp;

    //set up a test list with values 9->8->7->...->0
    for (i = 0; i < 10; i++)
    {
        temp = (Node*)malloc(sizeof(Node));
        if (temp == NULL)
        {
            printf("out of memory?\n");
            exit(1);
        }
        temp->data = i;
        temp->next = head;
        head = temp;
    }

    reverse(head);

    //print the reversed list.
    temp = head;
    while (temp != NULL)
    {
        printf("%d\n", temp->data);
        temp = temp->next;
    }

    return 0;
}

void reverse(Node* *head)
{
    Node* pre = NULL;
    Node* cur = NULL;
    Node* nex = NULL;

    pre = cur = nex = *head;
    pre = pre->next->next;
    cur = cur->next;
    nex->next = NULL;
    cur->next = nex;

    while(pre != NULL)
    {
        nex = cur;
        cur = pre;
        pre = pre->next;
        cur->next = nex;
    }

    *head = pre;

}  

最佳答案

事实上,您的 reverse() 函数不正确。它总是将 *head 分配给 NULL。永远。

while(pre != NULL)
{
    nex = cur;
    cur = pre;
    pre = pre->next;
    cur->next = nex;
}

终止此循环的唯一方法是如果 preNULL。然后你用它来分配给 *head:

*head = pre;

所以你的结果将始终是一个空列表。尝试将其设置为 cur

此外,您的函数不适用于空列表或单条目列表。正如注释所指出的,您需要传递头指针的地址 - reverse(&head)

关于c - 在C中反转链表,代码麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767873/

相关文章:

objective-c - 在 cocoa 中解析 ISO8601 日期的正确方法是什么?

c - 可以将实际参数定义为 `const int` 但在 header 中将其声明为 `int` 吗?

c - fgets 和 fread 的区别

c - 如何将用户界面添加到我的简单 C 代码中

c++ - Apple LLVM 4.1 的 STD 链接器错误

objective-c - subview 中的 NSView TouchesMovedWithEvent 正在暂停带有内置触控板的 SKScene,但不是魔术触控板?

android - 使用 -fPIC 链接静态 C 库并重新编译时出现错误

c - exit() 和 _exit() 的输出不同?

python - "TypeError: ' 设置 ' object is not callable"

ios - 从 OS X 向 iOS 发送通知