-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindromeLinkedList.cpp
More file actions
66 lines (60 loc) · 1.57 KB
/
palindromeLinkedList.cpp
File metadata and controls
66 lines (60 loc) · 1.57 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
/**
*Given a singly linked list, determine if it is a palindrome.
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head == NULL)
return true;
stack<int> s;
queue<int> q;
ListNode* cur = head;
while(cur != NULL)
{
s.push(cur->val);
q.push(cur->val);
cur = cur->next;
}
while(!s.empty())
{
if(s.top() != q.front())
return false;
s.pop();
q.pop();
}
return true;
}
};
bool isPalindrome(struct ListNode* head)
{
if(!head || !head->next) return true;
struct ListNode *slow=head, *fast=head->next->next;
while(fast && fast->next) //split into two halves while the right part might longer by 1 if the length of the link is odd;
{
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = NULL;
struct ListNode *cur, *pre, *next; //reverse the left linked and slow will become the head;
cur = head->next;
pre = head;
pre->next = NULL;
while(cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
if(fast->val != slow->val) fast = fast->next; //if the first node is unequal, move fast forward to the next;
while(fast)
{
if(fast->val != slow->val)
return false;
fast = fast->next;
slow = slow->next;
}
if(!fast || !slow) return false; //not all nodes have been compared - not symmetric;
return true;
}