请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
var isPalindrome = function(head) {
let preorder = "",
postorder = "";
const dfs = (node) => {
if(node == null) return;
preorder += node.val;
dfs(node.next);
postorder += node.val;
}
dfs(head);
return preorder === postorder;
};
//1. 将前半部分链表反转
//2. 判断前后两部分链表是否相等
var isPalindrome = function(head) {
if(!head) return true;
let pre = null,temp,fast = head,slow = head;
while(fast && fast.next){
fast = fast.next.next;
// 反转链表
temp = slow;
slow = slow.next;
temp.next = pre;
pre = temp;
}
if(fast) slow = slow.next;
while(pre && slow){
if(pre.val !== slow.val) return false;
pre = pre.next;
slow = slow.next;
}
return true;
};