题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路
1.遍历遍历
2.把链表每个节点数据存在ArrayList中
3.使用双指针遍历ArrayList
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ArrayList<Integer> list = new ArrayList<>();
ListNode cur = head;
while (cur != null) {
list.add(cur.val);
cur = cur.next;
}
int lo = 0;
int hi = list.size() - 1;
while (lo <= hi) {
if (!list.get(lo).equals(list.get(hi))) {
return false;
}
lo++;
hi--;
}
return true;
}
}