Palindrome Linked List
Given the head
of a singly linked list, return true
if it is a palindrome.
Example 1:
Input: head = [1,2,2,1] Output: true
Example 2:
Input: head = [1,2] Output: false
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//先把链表val拷贝进数组,再用双指针比较
ListNode cur = head;
List res = new ArrayList();
while (cur != null) {
res.add(cur.val);
cur = cur.next;
}
int front = 0;//头指针
int tail = res.size() - 1;//尾指针
while (front < tail) {
if (!(res.get(front) == res.get(tail))) {
return false;
}
front++;
tail--;
}
return true;
}
}