给你一个单链表的头节点 head ,请你判断该链表是否为
回文链表
。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
基本思路:计数法判断。先翻转后一半链表,判断是否回文,然后再反转回来。
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:bool isPalindrome(ListNode* head) {int n = 0;for(auto i = head; i; i = i->next) n ++;if(n == 1) return true;int half = n / 2;auto a = head;for(int i = 0; i < n - half; i ++ ) a = a->next;auto b = a->next;for(int i = 0; i < half - 1; i ++ ) {auto c = b->next;b->next = a;a = b; b = c;}auto p = head, q = a;bool success = true;for(int i = 0; i < half; i ++ ) {if(p->val != q->val) {success = false;break;}p = p->next;q = q->next;}auto tail = a;b = a->next;for(int i = 0; i < half - 1; i ++ ) {auto c = b->next;b->next = a;a = b, b = c;}tail->next = NULL;return success;}
};