Skip to content

234 回文链表 #55

@sailei1

Description

@sailei1

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

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法:
1 链表转换成数组
2 数组对称 比较

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    
    if(!(head&&head.next)){
        return true;
    }
    let node=head,arr=[];
    while(node){
       arr.push(node.val);    
        node=node.next;
    }  
    //转换成数组
    let t=true;
    
     for(let i=0;i<arr.length/2;i++) {
            if(arr[i] != arr[arr.length-1-i]) { //数组对称 比较
               t= false;
                break;
            }
     }
     return t;
    
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions