链表-简单:回文链表 By Swift

123 阅读1分钟

题目

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

示例 1:
输入: 1->2
输出: false

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

思路:

分以下三步:

  • 寻找前半段的最后一个节点。
  • 反转链表的后半部分。
  • 比较两个半段的链表。

代码:

class Solution {
    func isPalindrome(_ head: ListNode?) -> Bool {
        if head == nil {
            return true
        }
        let firstHalfEnd = findFirstHalfEnd(head)
        let secondHalfHead = reverse(firstHalfEnd?.next)
        
        var cur = head
        var secondCur = secondHalfHead
        var result = true
        
        while secondCur != nil && result {
            if secondCur?.val != cur?.val {
                result = false
            }
            secondCur = secondCur?.next
            cur = cur?.next
        }
        
        firstHalfEnd?.next = reverse(secondHalfHead)
        return result
    }
    
    func findFirstHalfEnd(_ head: ListNode?) -> ListNode? {
        var slow = head, fast = head
        while fast?.next != nil && fast?.next?.next != nil  {
            slow = slow?.next
            fast = fast?.next?.next
        }
        return slow
    }
    
    func reverse(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil {
            return head
        }
        
        var newHead: ListNode? = nil
        var cur = head
        var tempNext = head?.next
        
        while cur != nil {
            cur?.next = newHead
            newHead = cur
            cur = tempNext
            tempNext = tempNext?.next
        }
        return newHead
    }
}