-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathAnswer34.cpp
More file actions
76 lines (74 loc) · 1.67 KB
/
Answer34.cpp
File metadata and controls
76 lines (74 loc) · 1.67 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
70
71
72
73
74
75
class Solution {
Public:
ListNode *detectCycle(ListNode *head) {
if(!head){
return NULL;
}
ListNode* slow=head;
ListNode* fast=head;
slow=slow->next;
if(!fast->next){
return NULL;
}
fast=fast->next->next;
while(slow&&fast&&fast->next && slow!=fast){
slow=slow->next;
fast=fast->next->next;
}
fast=head;
while(slow&&fast&&slow!=fast){
slow=slow->next;aclass Solution {
public:
ListNode* reverse(ListNode* head){
ListNode* prev=NULL;
ListNode* next=NULL;
ListNode* curr=head;
ListNode* pass = head;
while(curr){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
}
bool isPalindrome(ListNode* head) {
if(!head){
return NULL;
}
ListNode* slow=head;
ListNode* fast=head;
if(!fast->next){
return true;
}
slow=slow->next;
fast=fast->next->next;
while(slow && fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
ListNode* q;
if(!fast){
q=reverse(slow);
}
else{
slow=slow->next;
q=reverse(slow);
}
while(q && head){
if(q->val==head->val){
head=head->next;
q=q->next;
}
else{
return false;
}
}
return true;
}
};
fast=fast->next;
}
return slow;
}
};