2 Star 2 Fork 1

Justin Yuan/LeetCode-Swift

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
PalindromeLinkedList.swift 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
/**
* Question Link: https://leetcode.com/problems/palindrome-linked-list/
* Primary idea: Runner tech, reverse the first half linkedlist, then compare it to the next half
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class PalindromeLinkedList {
func isPalindrome(_ head: ListNode?) -> Bool {
var slow = head, fast = head, dummy: ListNode? = nil
// reverse first half
while fast != nil && fast!.next != nil {
fast = fast!.next!.next
let nextNode = slow!.next
slow!.next = dummy
dummy = slow
slow = nextNode
}
// go to the starting point when length of list is odd
if fast != nil {
if slow == nil {
return true
}
slow = slow!.next
}
// compare reversed first and second half
while slow != nil {
if slow!.val != dummy!.val {
return false
} else {
slow = slow!.next
dummy = dummy!.next
}
}
return true
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/BiggerMax/LeetCode-Swift.git
git@gitee.com:BiggerMax/LeetCode-Swift.git
BiggerMax
LeetCode-Swift
LeetCode-Swift
master

搜索帮助