zoukankan      html  css  js  c++  java
  • 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
        }
    }
    
  • 相关阅读:
    Django Restframework 实践(二)
    mysql in 过滤 解决转义问题
    automapper
    autoface
    各种文件上传 转载
    REST Client
    MySql PartionBy
    mysql 变量名称不能与表字段一致
    mysql 存储过程分页 转载
    dapper.net 转载
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13857169.html
Copyright © 2011-2022 走看看