-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0234.cpp
More file actions
69 lines (62 loc) · 1.45 KB
/
0234.cpp
File metadata and controls
69 lines (62 loc) · 1.45 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
class Solution {
public:
bool isPalindrome(ListNode *head) {
if (head == nullptr || head->next == nullptr) {
return true;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *secondHalf = reverseList(slow);
ListNode *firstHalf = head;
while (secondHalf != nullptr) {
if (firstHalf->val != secondHalf->val) {
return false;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
return true;
}
ListNode *reverseList(ListNode *head) {
ListNode *prev = nullptr;
ListNode *curr = head;
while (curr != nullptr) {
ListNode *nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
};
/* old code (lower time but higher memory)*/
class Solution {
bool isPal(vector<int> &arr, int i, int j, int n) {
while (i >= 0 && j < n) {
if (arr[i] != arr[j])
return false;
i--;
j++;
}
return true;
}
public:
bool isPalindrome(ListNode *head) {
if (head == nullptr)
return false;
ListNode *p = head;
vector<int> vals;
while (p != nullptr) {
vals.push_back(p->val);
p = p->next;
}
int n = vals.size();
int i = (n % 2 == 0) ? n / 2 - 1 : n / 2;
int j = (n % 2 == 0) ? n / 2 : n / 2;
return isPal(vals, i, j, n);
}
};