-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234.swift
47 lines (43 loc) · 1.2 KB
/
234.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
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func isPalindrome(_ head: ListNode?) -> Bool {
if head?.next == nil { return true }
var fast = head
var slow = head
var leftlen = 0
while fast?.next != nil {
slow = slow?.next
fast = fast?.next?.next
leftlen += 1
}
// 右边的长度 >= 左边
var right = slow
var n = right?.next
var nn = right?.next?.next
right?.next = nil
while n != nil {
n!.next = right
right = n
n = nn
nn = n?.next
}
var left = head
for _ in 0..<leftlen {
if left!.val != right!.val {
return false
}
left = left!.next
right = right!.next
}
return true
}
}