Swift 回文链表 - LeetCode

《Swift 回文链表 - LeetCode》 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
    }
}
    原文作者:韦弦Zhy
    原文地址: https://www.jianshu.com/p/02cb1ebbe7d4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞