zoukankan      html  css  js  c++  java
  • leetcode 234. 回文链表 java

    题目:

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

    示例 1:

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

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

    解题:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isPalindrome(ListNode head) {    //画个图走一遍就懂了
            if(head == null || head.next == null) {
                return true;
            }
            ListNode slow = head, fast = head;    //快慢指针找到链表的中间位置
            ListNode pre = head, prepre = null;//专门设立两个指针用于反转链表
            while(fast != null && fast.next != null) {
                pre = slow;
                slow = slow.next;
                fast = fast.next.next;
                pre.next = prepre;    //反转前半部分链表
                prepre = pre;
            }
            if(fast != null) {    //对准中点
                slow = slow.next;
            }
            while(pre != null && slow != null) {
                if(pre.val != slow.val) {
                    return false;
                }
                pre = pre.next;
                slow = slow.next;
            }
            return true;
        }
    }
  • 相关阅读:
    selenium之 关闭窗口close与quit
    如何去掉xmind的备注红色下划线
    cmd里面快速粘贴复制的设置方式以及初始位置设置
    Python中的空格和缩进问题总结
    python 单例实现
    logging 简单使用
    CTypes
    类装饰器使用
    Django admin
    Django 视图
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11926471.html
Copyright © 2011-2022 走看看