码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] 234. Palindrome Linked List / Reverse linked list

时间:2020-01-23 09:28:20      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:term   param   cti   put   tac   func   head   algorithm   lock   

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

 

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    let slow = fast = head;
    let stack = [];
    
    while (fast && fast.next) {
        stack.push(slow.val);
        slow = slow.next;
        fast = fast.next.next;
    }
    
    if (fast) {
        slow = slow.next;
    }
    
    while (slow) {
        val = stack.pop();
        if (val !== slow.val) {
            return false
        }
        slow = slow.next;
    }
    
    return true;
};

 

Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    let slow = fast = head;
    
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    slow = reverse(slow);
    fast = head;
    
    while (slow) {
        if (slow.val !== fast.val) {
            return false
        }
        slow = slow.next;
        fast = fast.next;
    }
    
    return true;
}

var reverse = function (head) {
    let prev = null;
    
    while (head) {
        let next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    
    return prev;
}

[Algorithm] 234. Palindrome Linked List / Reverse linked list

标签:term   param   cti   put   tac   func   head   algorithm   lock   

原文地址:https://www.cnblogs.com/Answer1215/p/12230145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!