题目描述:请判断一个链表是否为回文链表。你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
代码实现
递归实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class Solution { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; }
ListNode node = head; int len = 0; while (node != null) { len++; node = node.next; }
node = head; int subLen = len / 2 + len % 2; while (subLen-- != 0) { node = node.next; }
ListNode subHead2 = reverse(node); ListNode subHead1 = head;
while (subHead1 != null && subHead2 != null) { if (subHead1.val != subHead2.val) { return false; } subHead1 = subHead1.next; subHead2 = subHead2.next; } return true; }
public ListNode reverse(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = reverse(head.next); head.next.next = head; head.next = null; return newHead; } }
|