Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func isPalindrome(_ head: ListNode?) -> Bool { var arr = Array(repeating: -1, count: 999999), p = head var i = 0, j = 0 while let q = p { arr[i] = q.val p = q.next; i+=1 } j = i-1; i = 0 while i < j { if arr[i] != arr[j] { return false } i+=1; j -= 1 } return true } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼