设计一种方式检查一个链表是否为回文链表。
再用原地反转解决一次
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @return a boolean
*/
ListNode * reverseList(ListNode * head) {
ListNode * p = head;
head = NULL;
while(p) {
ListNode * q = p;
p = p->next;
q->next = NULL;
q->next = head;
head = q;
}
return head;
}
void print(ListNode * head) {
while(head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
bool isPalindrome(ListNode* head) {
// Write your code here
if(head == NULL || head->next == NULL) {
return true;
}
ListNode * slow = head, * fast = head;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
if(fast) {
slow = reverseList(slow->next);
//print(slow->next);
} else {
slow = reverseList(slow);
//print(slow);
}
while(slow) {
if(head->val != slow->val) {
return false;
}
head = head->next;
slow = slow->next;
}
return true;
}
};
网友评论