Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
判断给定的链表是不是回文的:
把要判断的链表分成两部分,将第二部分逆置,逐个与前一部分的val相比较,若不同返回false
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head||!head->next)return true;
ListNode* slow=head;//这里定义slow,fast指针是为了寻找链表中间的位置
ListNode* fast=head;
while(fast->next&&fast->next->next){//假如链表有奇数个元素,则slow指针在循环后指向正中的元素;
//若链表有偶数个元素,则循环后slow指向n/2的元素位置
slow=slow->next;
fast=fast->next->next;
}
slow->next=reverse(slow->next);//将链表后面部分逆置
slow=slow->next;
while(slow){
if(head->val!=slow->val)return false;
head=head->next;
slow=slow->next;
}
return true;
}
ListNode* reverse(ListNode* head){
if(!head||!head->next)return head;
ListNode* pre=NULL;
ListNode* next=NULL;
while(head){
next=head-next;
head->next=pre;
pre=head;
head=next;
}
return pre;
}
};
贴个递归解法
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
bool flag = true;
recur_pal(head, head->next, flag);
return flag;
}
void recur_pal(ListNode *&head, ListNode *tail, bool &flag) {
if (head == tail || head == tail->next) return;
if (tail->next) {
recur_pal(head, tail->next, flag);
}
if (head->val != tail->val) { flag = false; return;}
head = head->next;
}