** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } * * O(n^2) rt and O(1) space. */
(head *ListNode)
| 14 | * O(n^2) rt and O(1) space. |
| 15 | */ |
| 16 | func isPalindrome(head *ListNode) bool { |
| 17 | if head == nil || head.Next == nil { |
| 18 | return true |
| 19 | } |
| 20 | |
| 21 | current := head |
| 22 | length := 0 |
| 23 | for current != nil { |
| 24 | length++ |
| 25 | current = current.Next |
| 26 | } |
| 27 | |
| 28 | current = head |
| 29 | front := head |
| 30 | for i := 0; i < length/2; i++ { |
| 31 | for j := 0; j < (length-1)-(2*i); j++ { |
| 32 | current = current.Next |
| 33 | } |
| 34 | |
| 35 | if front.Val != current.Val { |
| 36 | return false |
| 37 | } |
| 38 | |
| 39 | front = front.Next |
| 40 | current = front |
| 41 | } |
| 42 | |
| 43 | return true |
| 44 | } |
no outgoing calls