|
| 1 | +def is_palindrome(head): |
| 2 | + if not head: |
| 3 | + return True |
| 4 | + # split the list to two parts |
| 5 | + fast, slow = head.next, head |
| 6 | + while fast and fast.next: |
| 7 | + fast = fast.next.next |
| 8 | + slow = slow.next |
| 9 | + second = slow.next |
| 10 | + slow.next = None # Don't forget here! But forget still works! |
| 11 | + # reverse the second part |
| 12 | + node = None |
| 13 | + while second: |
| 14 | + nxt = second.next |
| 15 | + second.next = node |
| 16 | + node = second |
| 17 | + second = nxt |
| 18 | + # compare two parts |
| 19 | + # second part has the same or one less node |
| 20 | + while node: |
| 21 | + if node.val != head.val: |
| 22 | + return False |
| 23 | + node = node.next |
| 24 | + head = head.next |
| 25 | + return True |
| 26 | + |
| 27 | + |
| 28 | +def is_palindrome_stack(head): |
| 29 | + if not head or not head.next: |
| 30 | + return True |
| 31 | + |
| 32 | + # 1. Get the midpoint (slow) |
| 33 | + slow = fast = cur = head |
| 34 | + while fast and fast.next: |
| 35 | + fast, slow = fast.next.next, slow.next |
| 36 | + |
| 37 | + # 2. Push the second half into the stack |
| 38 | + stack = [slow.val] |
| 39 | + while slow.next: |
| 40 | + slow = slow.next |
| 41 | + stack.append(slow.val) |
| 42 | + |
| 43 | + # 3. Comparison |
| 44 | + while stack: |
| 45 | + if stack.pop() != cur.val: |
| 46 | + return False |
| 47 | + cur = cur.next |
| 48 | + |
| 49 | + return True |
| 50 | + |
| 51 | + |
| 52 | +def is_palindrome_dict(head): |
| 53 | + if not head or not head.next: |
| 54 | + return True |
| 55 | + d = {} |
| 56 | + pos = 0 |
| 57 | + while head: |
| 58 | + if head.val in d.keys(): |
| 59 | + d[head.val].append(pos) |
| 60 | + else: |
| 61 | + d[head.val] = [pos] |
| 62 | + head = head.next |
| 63 | + pos += 1 |
| 64 | + checksum = pos - 1 |
| 65 | + middle = 0 |
| 66 | + for v in d.values(): |
| 67 | + if len(v) % 2 != 0: |
| 68 | + middle += 1 |
| 69 | + else: |
| 70 | + step = 0 |
| 71 | + for i in range(0, len(v)): |
| 72 | + if v[i] + v[len(v) - 1 - step] != checksum: |
| 73 | + return False |
| 74 | + step += 1 |
| 75 | + if middle > 1: |
| 76 | + return False |
| 77 | + return True |
0 commit comments