您的位置 首页 JAVA(2017)

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;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 234. Palindrome Linked List》

发表评论

邮箱地址不会被公开。

返回顶部