#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the singly linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end of the list
void insertAtEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
// Function to display the linked list
void displayList(struct Node* head) {
if (head == NULL) {
printf("List is empty\n");
return;
}
printf("Linked List: ");
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Iterative function to reverse the linked list
void reverseIterative(struct Node** head) {
struct Node *prev = NULL, *current = *head, *next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead
prev = current;
current = next;
}
*head = prev;
printf("Linked list reversed iteratively\n");
}
// Recursive function to reverse the linked list
struct Node* reverseRecursiveUtil(struct Node* current, struct Node* prev) {
if (current == NULL) {
return prev;
}
// Store next
struct Node* next = current->next;
// Reverse current node's pointer
current->next = prev;
// Recurse for the remaining list
return reverseRecursiveUtil(next, current);
}
void reverseRecursive(struct Node** head) {
*head = reverseRecursiveUtil(*head, NULL);
printf("Linked list reversed recursively\n");
}
// Main function to test the linked list reversal
int main() {
struct Node* head = NULL;
// Create a linked list: 10 -> 20 -> 30 -> 40 -> 50
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtEnd(&head, 50);
printf("Original ");
displayList(head);
// Reverse the linked list iteratively
reverseIterative(&head);
displayList(head);
// Recreate the linked list for recursive reversal
head = NULL;
insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtEnd(&head, 40);
insertAtEnd(&head, 50);
printf("\nOriginal ");
displayList(head);
// Reverse the linked list recursively
reverseRecursive(&head);
displayList(head);
return 0;
}
Output:



No comments:
Post a Comment