-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathIs_palindrome
40 lines (40 loc) · 1.08 KB
/
Is_palindrome
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
bool findMidReverse(ListNode *head)
{
ListNode *fast, *slow;
fast = head;
slow = head;
while (fast->next != NULL && fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
// reverse
ListNode *prev, *curr, *nextptr;
curr = slow->next;
prev = NULL;
while (curr != NULL)
{
nextptr = curr->next;
curr->next = prev;
prev = curr;
curr = nextptr;
}
// compare
slow->next = prev;
ListNode *temp = head;
while (prev != NULL)
{
if (temp->val != prev->val)
{
return 0;
}
prev = prev->next;
temp = temp->next;
}
return 1;
}
bool isPalindrome(ListNode *head)
{
// find mid and reverse
return findMidReverse(head);
}