-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path234.cpp
More file actions
71 lines (55 loc) · 1.33 KB
/
234.cpp
File metadata and controls
71 lines (55 loc) · 1.33 KB
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
/*
* Written by Nitin Kumar Maharana
* nitin.maharana@gmail.com
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
int len;
void findLength(ListNode* head)
{
len = 0;
while(head)
{
len++;
head = head->next;
}
}
bool isPalindrome(ListNode *l, ListNode *r)
{
for(int i = 0; i < (len/2); i++)
{
if(l->val != r->val)
return false;
l = l->next;
r = r->next;
}
return true;
}
ListNode* reverseList(ListNode *head)
{
if(!head->next)
return head;
ListNode* h = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return h;
}
public:
bool isPalindrome(ListNode* head) {
findLength(head);
if(!len || (len == 1))
return true;
ListNode *ptr = head;
for(int i = 0; i < (len/2)-1; i++)
ptr = ptr->next;
ptr->next = reverseList(ptr->next);
return isPalindrome(head, ptr->next);
}
};