I've been trying to run this linkedListTraversal() function after reversing the linked list using the function reverseLinkedList(). I know that I'm applying the correct logic in the reverseLinkedList() function. But for some reason i'm getting the output as something like this
Here's my code
#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;
}