解题思路:
O(1)的空间复杂度,意味着不能通过开一个List来解决问题。我们可以把List分成前后两个部分,后半部分通过指针的相互赋值进行翻转即可。
JAVA实现如下:
public static boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; ListNode middle = head, fast = head; while (fast != null && fast.next != null) { middle = middle.next; fast = fast.next.next; } ListNode rightHalf = reverseListNode(middle); while (rightHalf != null) { if (rightHalf.val != head.val) return false; head = head.next; rightHalf = rightHalf.next; } return true; } public static ListNode reverseListNode(ListNode head) { if (head == null || head.next == null) return head; ListNode pre = head, cur = head.next, tmp = head; head.next = null; while (cur != null) { tmp = cur.next; cur.next = pre; pre = cur; cur = tmp; } return pre; }
时间: 2024-10-12 22:15:43