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?

    /**
     * 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) return true;
            ListNode slow = findmiddle(head);
            ListNode subhead = slow.next;
            slow.next = null;
            subhead = reverse(subhead);
            while(head != null && subhead != null && head.val == subhead.val){
                head = head.next;
                subhead = subhead.next;
            }
            if(subhead == null) return true;
            return false;
        }
        private static ListNode findmiddle(ListNode head){
            ListNode fast = head;
            ListNode slow = head;
            while(fast != null && fast.next != null && fast.next.next != null){
                fast = fast.next.next;
                slow = slow.next;
            }
            return slow;
        }
        private static ListNode reverse(ListNode head) {
            ListNode prev = null;
            while (head != null) {
                ListNode tmp = head.next;
                head.next = prev;
                prev = head;
                head = tmp;
            }
    
            return prev;
        }
    }

    findmiddle返回slow指针,指的是前半段最后一个node的位置,随后断开。后半段reverse,再把两段作比较,后半段长度只会小于等于前半段,所以后半段比较完就说明是palindrome。

  • 相关阅读:
    Elastic 技术栈之快速入门
    JDK8 指南(译)
    Intellij IDEA 使用小结
    面向对象1
    函数总结
    Python中i = i + 1与i + = 1的区别
    python中变量的交换
    python的数据类型的有序无序
    对列表里的字典按年龄从小到大排序
    centos7安装python3
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11392187.html
Copyright © 2011-2022 走看看