在使用函数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;
}