forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeLinkedList.swift
53 lines (45 loc) · 1.38 KB
/
PalindromeLinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 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
}
}