Swift 回文链表 - LeetCode

作者: 韦弦Zhy | 来源:发表于2018-11-27 17:33 被阅读62次
LeetCode

题目: 回文链表

请判断一个链表是否为回文链表。

示例1:

输入: 1->2
输出: false

示例2:

输入: 1->2->2->1
输出: true

进阶
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

方案:

便利链表,取出值val存入数组,便利数组对比头尾

代码:
/**
 * 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 {
    func isPalindrome(_ head: ListNode?) -> Bool {
        if head == nil {
            return true
        }
        var temp = head
        var listArray = [Int]()
        while temp != nil {
            listArray.append(temp!.val)
            temp = temp?.next
        }
        let count = listArray.count
        for i in 0...(count / 2) {
            if (listArray[i] != listArray[count-1-i]) {
                return false
            }
        }
        return true
    }
}

相关文章

网友评论

    本文标题:Swift 回文链表 - LeetCode

    本文链接:https://www.haomeiwen.com/subject/jihnqqtx.html