-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindromeLinkedList.c
90 lines (76 loc) · 2.05 KB
/
palindromeLinkedList.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* link;
} *head = NULL;
void addNode(int const data) {
struct Node* ptr = malloc(sizeof(struct Node));
ptr->data = data;
ptr->link = NULL;
if (head == NULL) {
head = ptr;
}
else {
struct Node* temp = head;
while (temp->link != NULL) {
temp = temp->link;
}
temp->link = ptr;
}
}
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* curr = head;
struct Node* next = NULL;
while (curr != NULL) {
next = curr->link;
curr->link = prev;
prev = curr;
curr = next;
}
return prev;
}
bool isPalindrome() {
if (head == NULL || head->link == NULL) {
// An empty list or a list with one node is a palindrome
return true;
}
// Step 1: Find the middle of the list
struct Node* slow = head;
struct Node* fast = head;
while (fast != NULL && fast->link != NULL) {
slow = slow->link;
fast = fast->link->link;
}
// Step 2: Reverse the second half of the list
struct Node* second_half = reverseList(slow);
// Step 3: Compare the two halves
struct Node* first_half = head;
struct Node* temp_second_half = second_half;
bool is_palindrome = true;
while (temp_second_half != NULL) {
if (first_half->data != temp_second_half->data) {
is_palindrome = false;
break;
}
first_half = first_half->link;
temp_second_half = temp_second_half->link;
}
// Step 4: Restore the list to its original order
reverseList(second_half);
return is_palindrome;
}
int main() {
int size, data;
printf("Enter the size of the Linked list: ");
scanf("%d", &size);
for (int i = 0; i < size; i++) {
printf("Enter the #%d of the list: ", i + 1);
scanf("%d", &data);
addNode(data);
}
printf("isPalindrome: %s\n", isPalindrome() ? "true" : "false");
return 0;
}