-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeLinkedList.cpp
More file actions
57 lines (51 loc) · 862 Bytes
/
PalindromeLinkedList.cpp
File metadata and controls
57 lines (51 loc) · 862 Bytes
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
//Given a singly linked list, determine if it is a palindrome.
//
//Follow up :
//Could you do it in O(n) time and O(1) space ?
#include<stddef.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class PalindromeLinkedList {
public:
bool isPalindrome(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
if (fast)
{
slow = slow->next;
}
slow = reverse(slow);
while (slow)
{
if (slow->val == head->val)
{
slow = slow->next;
head = head->next;
}
else
{
return false;
}
}
return true;
}
ListNode* reverse(ListNode* h){
ListNode* pre = NULL;
ListNode* t = NULL;
while (h){
t = h->next;
h->next = pre;
pre = h;
h = t;
}
return pre;
}
};