[LeetCode]Palindrome Linked List
反转后一半,然后判断,不过这样子会改变输入的数据,感觉不太好。也可以用一个栈,但是那样的话空间复杂度就不符合标准了。
/** * 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 || head.next == null) { return true; } int length = 0; ListNode p = head; while (p != null) { length ++; p = p.next; } p = head; ListNode pre = p; for (int i = 0; i < length / 2; i++) { pre = p; p = p.next; } if (length % 2 == 0) { pre.next = null; p = reverse(p); } else { pre.next = null; p = p.next; p = reverse(p); } while (head != null) { if (head.val != p.val) { return false; } head = head.next; p = p.next; } return true; } public ListNode reverse(ListNode head) { ListNode p2 = head; ListNode p1 = null; while (p2 != null) { ListNode tmp = p2; p2 = p2.next; tmp.next = p1; p1 = tmp; } return p1; } }