-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome Linked List.cpp
59 lines (55 loc) · 1.24 KB
/
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
56
57
58
59
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL) return true;
ListNode *slow, *fast;
slow = head;
fast = head->next;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode *p = head;
ListNode *q = slow->next;
slow->next = NULL;
ListNode *end = NULL;
while(q) {
ListNode *tmp = q->next;
q->next = end;
end = q;
q = tmp;
}
while(end) {
if(head->val != end->val) return false;
head = head->next;
end = end->next;
}
//if(head || end) return false;
return true;
}
};
int main() {
ListNode *head = new ListNode(3);
ListNode *tmp = head;
tmp->next = new ListNode(2);
tmp = tmp->next;
tmp->next = new ListNode(1);
tmp = tmp->next;
tmp->next = new ListNode(2);
tmp = tmp->next;
tmp->next = new ListNode(3);
tmp = tmp->next;
tmp->next = NULL;
Solution s;
cout << s.isPalindrome(tmp) << endl;
}