判断链表是否回文,有三种方法:
首先想到的是遍历链表,把链表值存放到数组中,首尾遍历即可。时间和空间复杂度都为O(N)。
用栈,将前一半链表数据入栈,然后判断出栈,与后半段链表依次比较。时间复杂度为O(N),空间复杂度为O(N/2)。
将后半段链表反转,然后比较两段链表的值,空间复杂度为O(1),符合题目要求。将链表分割成两部分,一般都用快慢指针实现。
代码如下:
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL){
return true;
}
ListNode* slow = head;
ListNode* fast = head;
while(fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
}
if(fast)//奇数个元素
{
slow = slow->next;
}
slow = reverse(slow);
while(slow != NULL)
{
if(head->val != slow->val)
{
return false;
}
head = head->next;
slow = slow->next;
}
return true;
}
ListNode* reverse(ListNode* head)
{
if(head==NULL || head->next==NULL){
return head;
}
ListNode* p = head->next;
head->next = NULL;
ListNode* pnext;
while(p!=NULL)
{
pnext = p->next;
p->next = head;
head = p;
p = pnext;
}
return head;
}