美文网首页Javascript in LeetCode
leetCode (js):234. 回文链表

leetCode (js):234. 回文链表

作者: i7eo | 来源:发表于2018-11-26 15:22 被阅读1次

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true
var isPalindrome = function(head) {
        var p = head,
            q = null,
            initVal = head;
        while(head) {
            var tmp = head;
            head = head.next;
            tmp.next = q;
            q = tmp;
        }

        if(JSON.stringify(initVal) === JSON.stringify(q)) return true;

        return false;
    };

思路是先把链表反转然后stringify,和之前的链表进行对比。但是leetcode在使用stringify时会报溢出错误,这个暂时不太清楚什么原因。下面列出网友的另一种思路:

var isPalindrome = function(head) {
    let first = '';
    let second = '';
    while (head) {
        first = first + head.val;
        second = head.val + second;
        head = head.next;
    }
    return first === second;
};

相关文章

  • 234. 回文链表

    234. 回文链表[https://leetcode.cn/problems/palindrome-linked-...

  • LeetCodeEmm

    234. 回文链表[https://leetcode-cn.com/problems/palindrome-lin...

  • 234. 回文链表

    234. 回文链表[https://leetcode-cn.com/problems/palindrome-lin...

  • Leetcode 234 回文链表

    234. 回文链表[https://leetcode-cn.com/problems/palindrome-lin...

  • leetCode (js):234. 回文链表

    请判断一个链表是否为回文链表。 示例 1: 示例 2: 思路是先把链表反转然后stringify,和之前的链表进行...

  • 如何判断回文链表

    读完本文,你可以去力扣拿下如下题目: 234.回文链表[https://leetcode-cn.com/probl...

  • LeetCode|234.回文链表

    题目描述 等级: 简单请判断一个链表是否为回文链表。 示例 1: 示例 2: 进阶:你能否用 O(n) 时间复杂度...

  • LeetCode 234. 回文链表

    234. 回文链表 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2输出: false 示例 2: 输...

  • Leetcode 234. 回文链表

    题目描述 请判断一个链表是否为回文链表。 示例 1: 输入: 1->2 输出: false 示例 2: 输入: 1...

  • LeetCode 234. 回文链表

    题目描述 请判断一个链表是否为回文链表。 示例1: 示例2: 题解

网友评论

    本文标题:leetCode (js):234. 回文链表

    本文链接:https://www.haomeiwen.com/subject/nhybqqtx.html