Total Accepted: 1116 Total Submissions: 4295 My Submissions Question Solution
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?
Hide Tags Linked List Two Pointers
【解题思路】
1、遍历链表,快慢指针,找到链表后半部分。
2、反转链表,能够參考Reverse Linked List
3、然后比較前半部分和后半部分的val值。
Java AC
/** * 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) { if (head == null) { return true; } ListNode slow = head; ListNode fast = slow.next; while (fast != null && fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode p = slow.next; ListNode q; ListNode end = null; while (p != null) { q = p.next; p.next = end; end = p; p = q; } while (head != null && end != null) { if (head.val != end.val) { return false; } head = head.next; end = end.next; } return true; } }