5.17
基本思想,就是遍历一遍链表,然后把每个节点的值存起来,在判断是不是回文。
最一开始想到的是字符串,这个想法就太简单了,没有考虑到负数会出现负号,也没有考虑到转化成为字符串,一个整数就被完全破坏了。
后来使用了ArrayList,这样就解决了字符串所带来的问题。
后来在比较两个数相等的时候,我又想当然的使用了!= 这个符号。以致总是出错。
对于Integer,Character,以及其他的很多这种封装的数据类型不能简单的使用 == 或者是 != 来判断是不是相等。
还是要使用equals函数。
类似的错误已经犯过一次了。希望自己这一次可以记住吖。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
//最开始使用了String类型
public boolean isPalindrome(ListNode head) {
// Write your code here
if(head == null || head.next == null){
return true;
}
ArrayList<Integer> list = new ArrayList<Integer>();
while(head != null){
list.add(head.val);
head = head.next;
}
int length = list.size();
//System.out.println("list:" + list);
for(int i = 0;i <= (length/2);i++){
//System.out.println("i:" + i + ";list[i]:" + list.get(i) + ";list[length -i -1]:"+ list.get(length - i -1));
if(!list.get(i).equals(list.get(length - i - 1))){
return false;
}
}
return true;
}
}