一、题解
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
可以考虑分为两步考虑:
(1)复制链表到数组列表中
(2)使用双指针判断是否是回文
二、代码
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list= new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode root= head;
while (root!= null) {
list.add(root.val);
root= root.next;
}
// 使用双指针判断是否回文
int first= 0;
int last= list.size() - 1;
while (first< last) {
if (!list.get(first).equals(list.get(last))) {
return false;
}
first++;
last--;
}
return true;
}
}
三、总结
Interger
包装类,不能直接使用==
比较,需要使用equals
public class Test {
public static void main(String[] args) {
Integer a = 1;
Integer b = 1;
System.out.println(a.equals(b));
}
}
(2)List 接口的常用操作:
List 接口继承 Collection 接口,所以 其中的
size()
方法也常用。