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?
先用2 pointer查找到中间点,然后后半部分reverse, 最后从head与中间点开始挨个check。此处要注意奇偶。
public bool IsPalindrome(ListNode head) { if(head == null) return true; ListNode slow = head; ListNode fast = head; ListNode nextNode = null; ListNode newHead = null; //get middle pointer of the linked list while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } while(slow != null) { nextNode = slow.next; slow.next = newHead; newHead = slow; slow = nextNode; } while(head != null && newHead != null) { if(head.val != newHead.val) return false; head = head.next; newHead = newHead.next; } return true; }