Given a singly linked list, determine if it is a palindrome.Example 1:code
Input: 1->2 Output: false Example 2:it
Input: 1->2->2->1 Output: trueio
由于题目要求用O(1)的空间, 因此首先找到中间点, 而后反转后半部分的链表, 而后和前半段链表对比.
另一种方法能够用一个stack, 找到中点以后将中点以后的数字都加进去而后一个一个拿出来.ast
时间O(n) 空间O(1)class
class Solution { public boolean isPalindrome(ListNode head) { if (head == null ) return true; ListNode fast = head, slow = head, pointer = head;; while (fast!= null && fast.next!= null) { fast = fast.next.next; slow = slow.next; } ListNode newHead = slow; ListNode res = reverse(newHead); while (res!= null) { if (res.val != head.val) { return false; } res = res.next; head = head.next; } return true; } public ListNode reverse(ListNode head) { ListNode pre = null; while (head != null) { ListNode tmp = head.next; head.next = pre; pre = head; head = tmp; } return pre; } }