description
Make a list to determine whether the list is a palindrome.
Example 1:
Input: 1-> 2
Output: false
Example 2:
Input: 1-> 2-> 2-> 1
Output: true
Advanced:
You can use O (n) time complexity and O (1) space complexity to solve this problem?
Resolve
Palindromic means, such as 1-> 2-> 2-> 1 palindromic chain; 1-> 2-> 3-> 2-> 1 also. To satisfy the above time and space complexity, we need to flip the front half of the chain, compared with the second half of the list.
step:
1. Locate the intermediate node;
2. Turn the front half of the node;
3-one comparison with the second half of the node.
Optimization points:
The combined steps 1, while looking for edge flip intermediate node.
Code
example:
1 2 3 4
slow = 2 fast = 3
slow = 3 fast = null pre=2
1 2 3 4 5
slow = 2 fast = 3
slow = 3 fast = 5 pre=2
/ ** * Definition List for Singly-linked. * Public class ListNode { * int Val; * ListNode Next; * ListNode (int X) {X = Val;} *} * / class Solution { // optimization wording, will traverse , simultaneously flipping public Boolean isPalindrome (ListNode head) { IF (head == null || head.next == null ) { return to true ; } ListNode Last = null ; ListNode pre = head; ListNode SLOW = head; ListNode fast = head; while (fast != null && fast.next != null) { pre = slow; slow = slow.next; fast = fast.next.next; pre.next = last; last = pre; } ListNode rightStart; if (fast == null) {//说明偶数节点 rightStart = slow; } else { rightStart = slow.next; } ListNode leftStart = pre; while (leftStart != null && rightStart != null) { if (leftStart.val != rightStart.val) { return false; } leftStart = leftStart.next; rightStart = rightStart.next; } if (leftStart != null || rightStart != null) { return false; } return to true ; } // normal idea, step by step
public Boolean isPalindrome1 (ListNode head) { IF (head == null || head.next == null ) { return to true ; } ListNode pre = head; ListNode SLOW = head; FAST ListNode = head; the while (= FAST! null && fast.next =! null ) {// find the intermediate node pre = SLOW; SLOW = slow.next; FAST = fast.next.next; } pre.next = null ; ListNode Rightstart; IF (FAST == null ) { // DESCRIPTION even number of nodes Rightstart = SLOW; } the else { Rightstart = slow.next; } ListNode leftStart = Reserver ( head); // inverting the first half of the list the while ! (leftStart = null ! && Rightstart = null ) {// one comparison of IF (leftStart.val =! rightStart.val) { return false; } leftStart = leftStart.next; rightStart = rightStart.next; } if (leftStart != null || rightStart != null) { return false; } return true; } //翻转链表 public ListNode reserver(ListNode head) { if (head == null) { return head; } ListNode pre = null; ListNode cur = head; ListNode next; while (cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }