Palindrome Linked List
Implement a function to check if a linked list is a palindrome.
Example
Given 1->2->1
, return true.
分析:
比较容易的方法是把所有的数存在ArrayList里,然后查看是否是palindrome,但是空间复杂度为O(n)。
还有就是先找到list的中点,然后把后半段reverse,然后再进行比较。但是这种方法不容易想到。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param head a ListNode 12 * @return a boolean 13 * cnblogs.com/beiyeqingteng 14 */ 15 public boolean isPalindrome(ListNode head) { 16 if(head == null || head.next == null) return true; 17 //find list center 18 ListNode mid = findMiddle(head); 19 20 ListNode secondHead = mid.next; 21 mid.next = null; 22 23 ListNode p = reverse(secondHead); 24 ListNode q = head; 25 while(p != null & q != null){ 26 if(p.val != q.val) { 27 return false; 28 } 29 p = p.next; 30 q = q.next; 31 } 32 return true; 33 } 34 35 private ListNode findMiddle(ListNode head) { 36 ListNode fast = head; 37 ListNode slow = head; 38 39 while(fast.next!=null && fast.next.next!=null){ 40 fast = fast.next.next; 41 slow = slow.next; 42 } 43 return slow; 44 } 45 46 private ListNode reverse(ListNode head) { 47 ListNode pre = null; 48 ListNode current = head; 49 ListNode next = null; 50 while (current != null) { 51 next = current.next; 52 current.next = pre; 53 pre = current; 54 current = next; 55 } 56 return pre; 57 } 58 }
转载请注明出处:cnblogs.com/beiyeqingteng/