Swift 3 solution


  • 0
    Y
    /**
     * 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 Solution {
        // 1->2->3->2->1
        // 1->2->3<-2<-1
        func isPalindrome(_ head: ListNode?) -> Bool {
            if head == nil {
                return true
            }
            // find the middle node
            var fast = head, slow = head
            while fast != nil {
                fast = fast?.next?.next
                slow = slow?.next
            }
            // reverse the second part of ListNode
            var pre: ListNode?
            var cur = slow
            while cur != nil {
                let next = cur?.next
                cur?.next = pre
                pre = cur
                cur = next
            }
            // pre is the new head of second part
            var p = head
            while p != nil && pre != nil {
                if p!.val != pre!.val {
                    return false
                }
                p = p?.next
                pre = pre?.next
            }
            return true
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.