★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-dcgbbryq-mc.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a singly linked list, determine if it is a palindrome.node
Example 1:git
Input: 1->2 Output: false
Example 2:github
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?微信
請判斷一個鏈表是否爲迴文鏈表。app
示例 1:spa
輸入: 1->2 輸出: false
示例 2:code
輸入: 1->2->2->1 輸出: true
進階:
你可否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?htm
72msblog
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var root = head 15 var stack = [ListNode]() 16 while root != nil { 17 stack.append(root!) 18 root = root?.next 19 } 20 21 var low = 0 22 var high = stack.count - 1 23 24 while low < high { 25 let lownode = stack[low] 26 let highnode = stack[high] 27 28 if lownode.val == highnode.val { 29 low += 1 30 high -= 1 31 } else { 32 return false 33 } 34 } 35 return true 36 } 37 }
56ms
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var slow = head 15 var fast = head 16 var reverse: ListNode? = nil 17 18 while fast?.next != nil { 19 fast = fast!.next!.next 20 let next = slow!.next 21 slow!.next = reverse 22 reverse = slow 23 slow = next 24 } 25 if fast != nil { 26 slow = slow!.next 27 } 28 29 while slow != nil { 30 if slow!.val != reverse!.val { 31 return false 32 } 33 slow = slow!.next 34 reverse = reverse!.next 35 } 36 37 return true 38 } 39 }
60ms
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * public var val: Int 5 * public var next: ListNode? 6 * public init(_ val: Int) { 7 * self.val = val 8 * self.next = nil 9 * } 10 * } 11 */ 12 class Solution { 13 func isPalindrome(_ head: ListNode?) -> Bool { 14 var slow = head 15 var fast = head 16 var reverse: [Int] = [Int]() 17 reverse.reserveCapacity(100) 18 19 while fast?.next != nil { 20 fast = fast!.next!.next 21 reverse.append((slow?.val)!) 22 slow = slow?.next 23 } 24 if fast != nil { 25 slow = slow!.next 26 } 27 28 while slow != nil { 29 if slow!.val != reverse.popLast() { 30 return false 31 } 32 slow = slow!.next 33 } 34 35 return true 36 } 37 }