Write a c program to check whether the created linked list is palindrome or not
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Define the structure for a node in the linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with given data
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end of the linked 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 print the linked list
void printList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}
// Function to reverse a linked list
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
// Function to check if the linked list is a palindrome
bool isPalindrome(struct Node* head) {
if (head == NULL || head->next == NULL) {
return true;
}
// Find the middle of the linked list
struct Node* slow = head;
struct Node* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
// Reverse the second half of the linked list
struct Node* secondHalf = reverseList(slow);
struct Node* firstHalf = head;
// Compare the first and second halves
while (secondHalf != NULL) {
if (firstHalf->data != secondHalf->data) {
return false;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
return true;
}
int main() {
struct Node* head = NULL;
// Inserting nodes into the linked list
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
insertAtEnd(&head, 2);
insertAtEnd(&head, 1);
printf("Linked list: ");
printList(head);
// Check if the linked list is a palindrome
if (isPalindrome(head)) {
printf("The linked list is a palindrome.\n");
} else {
printf("The linked list is not a palindrome.\n");
}
return 0;
}
Comments
Post a Comment