此代码检查链接列表是否为回文。当我比较列表中的两个大于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;}
添加回答
举报
0/150
提交
取消