zoukankan      html  css  js  c++  java
  • 回文链表(两总解法)

    判断是否是回文链表;

    import java.util.*;
    
    /*
     * public class ListNode {
     *   int val;
     *   ListNode next = null;
     * }
     */
    
    public class Solution {
        /**
         * 
         * @param head ListNode类 the head
         * @return bool布尔型
         */
         public boolean isPail (ListNode head) {
            // write code here
            if(head == null || head.next == null)
                return false;
             ListNode slow = head, fast = head.next;
             ListNode prev = null;
             while(fast != null && fast.next != null){
                 ListNode tmp = slow.next;
                 slow.next = prev;
                 prev = slow;
                 slow = tmp;
                 fast = fast.next.next;
             }
             // 奇数与偶数分类讨论
             // 奇数时候,slow停在正中间,(slow位置不满足,因此这个点与后面链表相连),因此要后移一位
             // 偶数的时候,slow停在中间靠左边,(slow位置)
             // slow 指针指向的元素永远是等待处理的元素,指向的位置,都还没有和前面连起来,指过的位置才已经连起来了。
             ListNode l2 = slow;
             ListNode l1 = prev;
             if(fast == null){
                 l2 = l2.next;
             } else{
                 l2 = slow.next;
                 slow.next = prev;
                 l1 = slow;
             }
             while(l1 != null && l2 != null){
                 if(l1.val != l2.val)
                        return false;
                 l1 = l1.next;
                 l2 = l2.next;
             }
             return true;
                
        }
        
        
        
        public boolean isPail2(ListNode head) {
            // write code here
            ArrayList<ListNode> list = new ArrayList<> ();
            while(head != null){
                list.add(head);
                head = head.next;
            }
            int i = 0, j = list.size() -1;
            while( i < j){
                if(list.get(i).val != list.get(j).val){
                    return false;
                }
                i++;
                j--;
            }
            return true;
        }
    }
    
    
  • 相关阅读:
    svn中trunk、branches、tags
    支付宝支付对接过程
    分享插件
    ES6学习笔记
    VS code
    Angular45
    React笔记
    查询Table name, Column name, 拼接执行sql文本, 游标, 存储过程, 临时表
    通过脚本把远程服务器上的表和数据拷贝到本地数据库
    mongo客户端mongo VUE增删改查
  • 原文地址:https://www.cnblogs.com/sidewinder/p/13715792.html
Copyright © 2011-2022 走看看