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

    public class PalindromeLinkedList {
        /*
        解法一:可能刚开始刷题的原因,想到的老是这种简单的笨办法。
         */
    
        public static boolean isPalindrome(ListNode head) {
            if(head==null||head.next==null)
                return true;
            ListNode temp=head;
            List<Integer> list=new ArrayList<>();
            while (temp!=null){
                list.add(temp.val);
                temp=temp.next;
            }
            temp=head;
            for (int i=list.size()-1;i>=0;i--){
                if (temp.val!=list.get(i).intValue())
                    return false;
                temp=temp.next;
            }
            return true;
        }
    
       
        /*
        解法二:用快慢指针找到链表中点,同时反转前半部分,然后依次从中点向两边回文检验。
         */
        public boolean isPalindrome2(ListNode head) {
            if (head==null||head.next==null)
                return true;
            ListNode slow=head;
            ListNode fast=head.next;
            ListNode previous=null;
            ListNode next=null;
            while (fast!=null&&fast.next!=null){
                next=slow.next;
                slow.next=previous;
                previous=slow;
                slow=next;
                fast=fast.next.next;
            }
            ListNode right=slow.next;
            ListNode left=null;
            if (fast==null)
                left=previous;
            else{
                slow.next=previous;
                left=slow;
            }
            while (left!=null){
                if (left.val!=right.val)
                    return false;
                left=left.next;
                right=right.next;
            }
            return true;
        }
    }
  • 相关阅读:
    TeX中的引号
    竖式问题
    蛇形填数
    开灯问题
    排列
    分数化小数
    子序列的和
    cookie
    post请求
    get请求
  • 原文地址:https://www.cnblogs.com/zhangyuhao/p/11441558.html
Copyright © 2011-2022 走看看