LeetCode – 234. Palindrome Linked List

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;
    }
}

邮件订阅,随时获取更新信息

发表评论

电子邮件地址不会被公开。

This site uses Akismet to reduce spam. Learn how your comment data is processed.