Loading

回文链表(两总解法)

判断是否是回文链表;

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;
    }
}

posted @ 2020-09-23 01:24  Sidewinder  阅读(195)  评论(0编辑  收藏  举报