题目描述
编写一个函数,检查输入的链表是否是回文的。
我的解法
逆向后半部分字符串,逐一比较
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseListNode(ListNode *head)
{
if(head==nullptr || head->next==nullptr) return head;
ListNode *p=head, *q=p->next, *r=q->next;
p->next = nullptr;
while(q!=nullptr)
{
r = q->next;
q->next=p;
p=q;
q=r;
}
return p;
}
bool isPalindrome(ListNode* head) {
if(head==nullptr || head->next==nullptr) return true;
int count=0;ListNode *p = head;
while(p!=nullptr){
count++;
p=p->next;
}
int halflength = (count&0x01)==0?count/2: count/2+1;
ListNode *q = head;
while(halflength-->0) q=q->next;
q = reverseListNode(q);
p=head;
while(q!=nullptr)
{
if(q->val!=p->val) return false;
q=q->next;p=p->next;
}
return true;
}
};
执行用时 :32 ms, 在所有 C++ 提交中击败了26.17%的用户
内存消耗 :16.1 MB, 在所有 C++ 提交中击败了100.00%的用户