zoukankan      html  css  js  c++  java
  • 234. Palindrome Linked List

    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

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

    找中点,反转后半部分,再一一比较

    time: O(n), space: O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null || head.next == null) {
                return true;
            }
            ListNode fast = head, slow = head;
            while(fast.next != null && fast.next.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            ListNode p1 = head, p2 = reverse(slow.next);
            slow.next = null;
            while(p1 != null && p2 != null) {
                if(p1.val != p2.val) {
                    return false;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            return true;
        }
        
        private ListNode reverse(ListNode head) {
            if(head == null || head.next == null) {
                return head;
            }
            ListNode prev = null, cur = head;
            while(cur != null) {
                ListNode next = cur.next;
                cur.next = prev;
                prev = cur;
                cur = next;
            }
            return prev;
        }
    }
  • 相关阅读:
    php 魔术方法
    有用的函数系统采集(一)
    php后期静态绑定
    php对象引用及序列化
    php文件操作
    复习mysql视图总结
    jQuery调用WebService详解
    这个网站的界面描述甚好,我喜欢
    喜欢和技术有关的一切~
    Introduction
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10178105.html
Copyright © 2011-2022 走看看