andavid/leetcode-java

如果是奇数个的回文的话判断是会不准吧

EthanHuntDeng opened this issue · 2 comments

如果是奇数个的回文的话判断是会不准吧
public static Boolean is(Node head){

    if(head == null || head.next == null){
        return true;
    }
    Node prev =  null;
    Node fast = head;
    Node slow = head;
    Boolean a = false;
    while (fast != null ){
        if(fast.next!=null){
            fast = fast.next.next;
        }else{
            fast = null;
            a = true;
        }

        Node node = slow.next;
        slow.next=prev;
        prev = slow;
        slow = node;
    }
    Node midalNode = slow;
    if(!a){
        midalNode = slow.next;
    }
    while (midalNode != null){
        if(!midalNode.s.equals(prev.s)){
            return false;
        }
        midalNode = midalNode.next;
        prev = prev.next;
    }
    return true;
}

这样写就没问题了,不管中间数是偶数还是奇数都可以搞定了

public class Solution {
public static boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}

    ListNode prev = null;
    ListNode slow = head;
    ListNode fast = head;

    while (fast != null && fast.next != null) {
        fast = fast.next.next;
        ListNode next = slow.next;
        slow.next = prev;
        prev = slow;
        slow = next;
    }

    if (fast != null) {

        ListNode mid = slow;
        slow = slow.next;
        mid.next = prev;
        prev = mid;

    }

    if (fast == null) {

        slow = slow.next;

    }

    while (slow != null) {
        if (slow.val != prev.val) {
            return false;
        }
        slow = slow.next;
        prev = prev.next;
    }

    return true;
}