1

在使用函数reverseLinkedList() 反转链表之后,我一直在尝试运行这个linkedListTraversal() 函数。我知道我在 reverseLinkedList() 函数中应用了正确的逻辑。但由于某种原因,我得到的输出是这样的 我的输出

这是我的代码

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

struct Node
{  
   int data;
   struct Node *next;
};
// struct Node *head;

void linkedListTraversal(struct Node *ptr) 
{
// struct Node *ptr = head;
   while (ptr != NULL)
   {
       printf("Element: %d\n", ptr->data);
       ptr = ptr->next;
   }
}

void reverseLinkedList(struct Node *head)
{
    struct Node *prevNode = NULL;
    struct Node *currNode = head;
    struct Node *nextNode;

    while (currNode != NULL)
    {
       nextNode = currNode->next;
       currNode->next = prevNode;
       prevNode = currNode;
       currNode = nextNode;
    }

    head = prevNode;
}

int main()
{
    struct Node *head;
    struct Node *second;
    struct Node *third;

    head = (struct Node *)malloc(sizeof(struct Node));
    second = (struct Node *)malloc(sizeof(struct Node));
    third = (struct Node *)malloc(sizeof(struct Node));

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

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

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

    printf("Linked list before reversal: \n");
    linkedListTraversal(head);

    reverseLinkedList(head);

    printf("Linked list after reversal: \n");
    linkedListTraversal(head);
    return 0;
 }
4

1 回答 1

2

不会将更新 head的内容传回main.

最简单的方法returnhead

struct Node *reverseLinkedList(struct Node *head);

并且有main做:

head = reverseLinkedList(head);

旁注:无需转换结果malloc我是否转换了 malloc 的结果?这是一种更惯用的分配方式(例如):

head = malloc(sizeof(*head));

这是完整的代码:

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

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

// struct Node *head;

void
linkedListTraversal(struct Node *ptr)
{
// struct Node *ptr = head;
    while (ptr != NULL) {
        printf("Element: %d\n", ptr->data);
        ptr = ptr->next;
    }
}

struct Node *
reverseLinkedList(struct Node *head)
{
    struct Node *prevNode = NULL;
    struct Node *currNode = head;
    struct Node *nextNode;

    while (currNode != NULL) {
        nextNode = currNode->next;
        currNode->next = prevNode;
        prevNode = currNode;
        currNode = nextNode;
    }

    head = prevNode;

    return head;
}

int
main(void)
{
    struct Node *head;
    struct Node *second;
    struct Node *third;

    head = malloc(sizeof(*head));
    second = malloc(sizeof(*second));
    third = malloc(sizeof(*third));

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

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

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

    printf("Linked list before reversal: \n");
    linkedListTraversal(head);

    head = reverseLinkedList(head);

    printf("Linked list after reversal: \n");
    linkedListTraversal(head);

    return 0;
}
于 2022-02-24T21:35:59.500 回答