zoukankan      html  css  js  c++  java
  • [LC] 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

    /**
     * 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;
            }
            
            // get middle node
            ListNode fast = head.next, slow = head;
            while (fast != null && fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            }
            ListNode mid = slow;        
            
            // revert from mid next
            mid.next = revert(mid.next);
            ListNode aNode = head;
            ListNode bNode = mid.next;
            while(aNode != null && bNode != null) {
                if (aNode.val != bNode.val) {
                    return false;
                }
                aNode = aNode.next;
                bNode = bNode.next;
            }
            return true;
        }
        
        private ListNode revert(ListNode head) {
            ListNode pre = null, nxt = null;
            while(head != null) {
                nxt = head.next;
                head.next = pre;
                pre = head;
                head = nxt;
            }
            return pre;
        }
    }
  • 相关阅读:
    Fiddler工具抓包
    简单Ant打包
    android中ActionBar的几个属性
    yum安装php7.2
    java 获取计算机内存
    docker apache安装
    docker 安装 openresty
    docker 安装nginx
    docker安装gitlab
    java获取时间格式
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12123663.html
Copyright © 2011-2022 走看看