leetcode刷题笔记 234题 回文链表

leetcode刷题笔记 234题 回文链表

源地址:234. 回文链表

问题描述:

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

示例 1:

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

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
object Solution {
    def isPalindrome(head: ListNode): Boolean = {
        //特殊情况直接返回
        if (head == null || head.next == null) return true
		
        //通过快慢指针找寻中间节点
        var fast = head.next
        var slow = head
        while (fast != null && fast.next != null){
            slow = slow.next
            fast = fast.next.next
        }
        
        //尝试对右半链表进行颠倒
        slow = slow.next
        //使用特殊值标记新节点
        var newHead = new ListNode(-99)

        while (slow!= null) {
            val tempNode =  slow.next
            slow.next = newHead
            newHead = slow
            slow = tempNode            
        }
		
        //逐个节点比较 
        var oldHead = head
        while (newHead != null) {
            if (newHead.x != -99 && oldHead.x != newHead.x) return false
            oldHead = oldHead.next
            newHead = newHead.next
        }
        return true
    }
}
posted @ 2020-10-22 11:22  ganshuoos  阅读(63)  评论(0编辑  收藏  举报