# 【LeetCode】234. 回文链表

·  阅读 431

## 题目描述

234. 回文链表 - 力扣（LeetCode）

## 示例 & 提示

``````输入：head = [1,2,2,1]

``````输入：head = [1,2]

• 链表中节点数目在范围`[1, 105]` 内
• `0 <= Node.val <= 9`

## 思路

• 暴力就是把链表值复制到一个数组里，然后双指针比较

• 首先我们需要找到中间结点，然后将后面的结点逆置，前段和后段对比即可

• 又或者我们可以换个思路，比如在找中间结点的时候逆置前半部分？这样如果是奇数个元素，需要多判断一下

• 最后还有递归做法，我们都知道可以用递归反向打印链表，思路这不就有了

## 具体代码

``````bool isPalindrome(struct ListNode *head) {
return true;
}

while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}

pre = slow;
slow = slow->next;
pre->next = NULL;
while (slow != NULL) {
tmp = slow->next;
slow->next = pre;
pre = slow;
slow = tmp;
}

while (pre != NULL) {
return false;
}
pre = pre->next;
}
return true;
}

``````bool isPalindrome(struct ListNode *head) {
return true;
}

struct ListNode *slow = head, *fast = head, *pre = NULL, *cur;
while (fast != NULL && fast->next != NULL) {
cur = slow;
slow = slow->next;
fast = fast->next->next;

cur->next = pre;
pre = cur;
}

if (fast != NULL) {
slow = slow->next;
}

while (cur != NULL) {
if (cur->val != slow->val) {
return false;
}
cur = cur->next;
slow = slow->next;
}
return true;
}

``````struct ListNode *tmp;
return true;
}
tmp = tmp->next;
return res;
}