zoukankan      html  css  js  c++  java
  • 回文链表

      

    请判断一个链表是否为回文链表。

    示例 1:

    输入: 1->2
    输出: false

    示例 2:

    输入: 1->2->2->1
    输出: true

    public static boolean isPalindrome(ListNode head){
            ListNode fast=head;
            ListNode slow=head;
            while (fast!=null&&fast.next!=null){
                slow=slow.next;
                fast=fast.next.next;
            }
            ListNode slowHead=slow;
            ListNode reverse=reverse(slow);
            ListNode h=head;
            while (h!=slowHead){
                if(h.val!=reverse.val){
                    return false;
                }
                h=h.next;
                reverse=reverse.next;
            }
            return true;
        }
    View Code
    static ListNode reverse(ListNode head){
            ListNode curr=head;
            ListNode pre=null;
            while (curr!=null){
                ListNode temp=curr.next;
                curr.next=pre;
                pre=curr;
                curr=temp;
            }
            return pre;
        }
    View Code
    @Data
        static class ListNode{
            private int val;
            private ListNode next;
    
            public ListNode(int value){
                this.val=value;
            }
        }
    View Code

      主要思路是

      1.先通过快慢指针(慢指针一次走一步,快指针一次走2步),找到后半段链表。

      2.把后半段链表反转。

      3.对比前半段链表和后半段链表是否一样,不一样返回false。

  • 相关阅读:
    Centos7.2安装MariaDB数据库,并进行基础配置
    Web安全之环境搭建
    PHP构建一句话木马
    Spark2.1.0安装
    Spark2.1.0编译
    cdh-5.10.0搭建安装
    八、频繁模式挖掘Frequent Pattern Mining
    七、特征提取和转换
    六、降维
    五、聚类
  • 原文地址:https://www.cnblogs.com/wuyouwei/p/11766384.html
Copyright © 2011-2022 走看看