-
Notifications
You must be signed in to change notification settings - Fork 1
/
234_Palindrome_Linked_List.cpp
55 lines (43 loc) · 1.1 KB
/
234_Palindrome_Linked_List.cpp
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
// https://leetcode.com/problems/palindrome-linked-list/
// https://leetcode.com/problems/palindrome-linked-list/discuss/1923879/A-Unique-Recursive-Solution-or-Simple-Logic-(-)
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode *p = NULL;
void helper(ListNode *head, bool &isPalin)
{
if (head == NULL)
return;
helper(head->next, isPalin);
if (p->val != head->val)
{
isPalin = false;
return;
}
p = p->next;
}
bool isPalindrome(ListNode *head)
{
p = head;
bool isPalin = true;
helper(head, isPalin);
return isPalin;
}
int main()
{
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(3);
head->next->next->next->next = new ListNode(2);
head->next->next->next->next->next = new ListNode(1);
cout << isPalindrome(head) << '\n';
return 0;
}