234. Palindrome Linked List - Easy
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?
找中点,反转后半部分,再一一比较
time: O(n), space: O(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) { if(head == null || head.next == null) { return true; } ListNode fast = head, slow = head; while(fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } ListNode p1 = head, p2 = reverse(slow.next); slow.next = null; while(p1 != null && p2 != null) { if(p1.val != p2.val) { return false; } p1 = p1.next; p2 = p2.next; } return true; } private ListNode reverse(ListNode head) { if(head == null || head.next == null) { return head; } ListNode prev = null, cur = head; while(cur != null) { ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }