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;
        }
    }
    
    
  • 相关阅读:
    开源权限框架shiro 入门
    Struts1.2入门笔记
    memcache概述
    教你如何将中文转换成全拼
    WPF第一章(XAML前台标记语言(Chapter02代码讲解))
    WPF第一章(XAML前台标记语言)
    WPF简介
    Activity以singleTask模式启动,intent传值的解决办法
    linux下查看文件编码以及编码转换
    Fedora 17字体美化
  • 原文地址:https://www.cnblogs.com/sidewinder/p/13715792.html
Copyright © 2011-2022 走看看