-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkPalindromeLinkedList.c
98 lines (85 loc) · 2.07 KB
/
checkPalindromeLinkedList.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
91
92
93
94
95
96
97
98
#include <stdio.h>
#include <stdlib.h>
typedef struct elementT {
struct elementT *next;
int data;
} element;
int isPalindromeRec(element *head) {
return isPalindromeRecSub(&head, head);
}
int isPalindromeRecSub(element **left, element *right) {
if(!right)
return 1;
int r = isPalindromeRecSub(left, right->next);
if(r == 0)
return 0;
int r2 = (right->data == (*left)->data);
*left = (*left)->next;
return r2;
}
void reverse(element **mid) {
element *pre = NULL, *curr = *mid, *next = NULL;
while(curr != NULL) {
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
*mid = pre;
}
int compare(element *left, element *right) {
element *e1 = left, *e2 = right;
while(e1 && e2) {
if(e1->data == e2->data) {
e1 = e1->next;
e2 = e2->next;
} else
return 0;
}
if(e1 == NULL && e2 == NULL)
return 1;
return 0;
}
int isPalindrome(element *head) {
if(head == NULL)
return 1;
element *slow = head, *fast = head, *pre = head, *mid = NULL;
while(fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
int res;
// we have even no of elements.
if(fast->next != NULL) {
mid = slow->next;
reverse(&mid);
slow->next = NULL;
res = compare(head, mid);
reverse(&mid);
slow->next = mid;
} else {
mid = slow->next;
pre->next = NULL;
reverse(&mid);
res = compare(head, mid);
reverse(&mid);
pre->next = slow;
slow->next = mid;
}
return res;
}
element *makeNode(int d) {
element *ele = (element *)malloc(sizeof(element));
ele->data = d;
return ele;
}
main()
{
element *h = makeNode(5);
h->next = makeNode(6);
h->next->next = makeNode(6);
h->next->next->next = makeNode(5);
//h->next->next->next->next = makeNode(5);
printf("%d %d\n", isPalindromeRec(h), isPalindrome(h));
}