Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
这道题目难在follow up上
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
ListNode res = rev(head);
return checksame(head,res);
}
public ListNode rev(ListNode head){
ListNode result = null;
while(head != null){
ListNode n = new ListNode(head.val);
n.next = result;
result = n;
head = head.next;
}
return result;
}
public boolean checksame(ListNode a, ListNode b){
while(a != null && b != null){
if(a.val != b.val){
return false;
}
a = a.next;
b = b.next;
}
return true;
}
}
微信扫一扫
支付宝扫一扫