请判断一个链表是否为回文链表。
示例 1:
- 输入: 1->2
- 输出: false
示例 2:
- 输入: 1->2->2->1
- 输出: true
题解:
运用快慢指针找到链表中心节点,然后将链表一分为二,将后半段链表倒转后进行比较。
/**
* 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==NULL||head->next==NULL){
return true;
}
ListNode *pre = head;
ListNode *lat = head->next;
while(lat!=NULL&&lat->next!=NULL){
pre = pre->next;
lat = lat->next->next;
}
ListNode *cur = pre->next;
pre->next = NULL;//break the listnode
ListNode *p = NULL;
while(cur!=NULL){
ListNode *q = cur->next;
cur->next = p;
p = cur;
cur = q;
}
while(p!=NULL&&head!=NULL){
if(p->val==head->val){
p = p->next;
head = head->next;
}
else{
return false;
}
}
return true;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list