Hi,
I am trying to solve this problem:

I find the length of the list.

I reverse the second half.

I compare the first half with the second one.
Here is my implementation. I get TLE but apparently my program stops (I've put some printf to test it).class Solution {
private:
int getLen(ListNode *head) {
ListNode *current = head;
int num = 0;
while (current) {
++num;
current = current>next;
}
return num;
}ListNode* getLast(ListNode *head) { ListNode *current = head; if (current == NULL) { return NULL; } while (current>next) { current = current>next; } return current; } void reverse(ListNode *head, int N) { ListNode *current = head; while (N) { current = current>next; } ListNode *aux = current>next; while (aux) { ListNode *temp = aux > next; aux > next = current; current = aux; aux = temp; } } bool solve(ListNode *head, ListNode *last, int N) { ListNode *left = head; ListNode *right = last; while (N) { cout << N << "\n"; cout << "left = " << left>val << "...right = " << right>val << "\n"; if (left>val != right>val) { return false; } left = left>next; right = right>next; } return true; }
public:
bool isPalindrome(ListNode* head) {
cout << "Here\n";
int N = getLen(head);
cout << "N = " << N<< "\n";
ListNode *last = getLast(head);
cout << "getLast\n";
if (last == nullptr) {
return true;
}
if (N/2 == 0) {
if (head>next) {
return head>val == head>next>val;
}
return true;
}
reverse(head, N  N/2);
cout << "reverse\n";return solve(head, last, N/2); }
};
For the input 1>2>2>1
The output is:Here
N = 4
getLast
reverse
1
left = 1...right = 1
0
left = 2...right = 2
Any hint is useful.
Many thanks,
Ioana