猿问

Java-通用链表值比较在值大于127时失败

此代码检查链接列表是否为回文。


当我比较列表中的两个大于127的值时,它将返回该值始终不相等,例如运行[1,128,100,100,128,1],该代码将返回128!= 128,除非我在if语句中将它们强制转换为int。


我只是好奇为什么会这样。这是我的代码:


while(firstHalf != null && secondHalf != null)

    {

        //COMPARISON ONLY WORKS WHEN CASTED TO AN INT

        if(((int)firstHalf.value) != ((int)secondHalf.value))

        {

            return false;

        }

        firstHalf = firstHalf.next;

        secondHalf = secondHalf.next;

    }

整个方法:


// Definition for singly-linked list:

// class ListNode<T> {

//   ListNode(T x) {

//     value = x;

//   }

//   T value;

//   ListNode<T> next;

// }

//

boolean isListPalindrome(ListNode<Integer> l) {

    if(l == null)

        return true;


    ListNode fastPnter = l;

    ListNode slowPnter = l;

    ListNode slowPnterPrev = l;


    //find mid point

    while(fastPnter != null && fastPnter.next !=null)

    {

        fastPnter = fastPnter.next.next;

        slowPnterPrev = slowPnter;

        slowPnter = slowPnter.next;

    }


    //odd case

    if(fastPnter != null)

    {

        slowPnterPrev = slowPnter;

        slowPnter = slowPnter.next;

    }


    //reverse second half

    slowPnterPrev.next = null;

    ListNode midNode = reverse(slowPnter);


    //check halves

    ListNode firstHalf = l;

    ListNode secondHalf = midNode;

    while(firstHalf != null && secondHalf != null)

    {

        //COMPARISON ONLY WORKS WHEN CASTED TO AN INT

        if(((int)firstHalf.value) != ((int)secondHalf.value))

        {

            return false;

        }

        firstHalf = firstHalf.next;

        secondHalf = secondHalf.next;

    }


    return true;

}


慕沐林林
浏览 172回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答