Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
方法1:(常规方法)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head! = null){
list.add(head.val);
head = head.next;
}
return isPalindromeList(list);
}
public boolean isPalindromeList(List<Integer> list){
int i = 0;
int j = list.size()-1;
while(i < j){
if(list.get(i) != list.get(j)){
return false;
}
}
return true;
}
}
时间复杂度:O(n)
空间复杂度:O(n)