请判断一个链表是否为回文链表。
示例
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
题解
遍历链表,记录到数组中,通过数组翻转判断是否是回文
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
var arr = []
let p = head
while (p) {
arr.push(p.val)
p = p.next
}
return arr.join('') === arr.reverse().join('')
};
另一种 通过快慢指针找到中间节点,在记录遍历过的翻转节点,对比他们是否同一链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
if (head == null || head.next == null) {
return true
}
let fast = head, slow = head, pre = head, prever = null
while (fast !== null && fast.next !== null) {
pre = slow
fast = fast.next.next
slow = slow.next
pre.next = prever
prever = pre
}
if (fast !== null) {
slow = slow.next
}
while (pre != null && slow != null) {
if (pre.val !== slow.val) {
return false
}
pre = pre.next
slow = slow.next
}
return true
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。