zoukankan      html  css  js  c++  java
  • 判断一个链表是否是回文链表,时间复杂度O(n),空间复杂度O(1)

    leetcode234

    思路:(1)快慢指针找到链表中点(2)原地反转中点之后的链表(3)比较两段链表的值(4)反转的链表再反转回去

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
     // O(n) 时间复杂度和 O(1) 空间复杂度
    class Solution {
        public boolean isPalindrome(ListNode head) {
            if(head == null){
                return true;
            }
            //1.快慢指针找到链表中点
            ListNode slow = head;
            ListNode fast = head;
            while(fast.next != null && fast.next.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            //2.将后半部分的链表反转
            ListNode curNode = slow.next;
            ListNode pre = null;
            while(curNode != null){
                ListNode nextNode = curNode.next;
                curNode.next = pre;
                pre = curNode;
                curNode = nextNode;
            }
            slow.next = pre;
            ListNode leftNode = head;
            ListNode rightNode = pre;
            while(leftNode != null && rightNode != null){
                if(leftNode.val != rightNode.val){
                    return false;
                }
                leftNode = leftNode.next;
                rightNode = rightNode.next;
            }
            //3.将反转后的链表反转回来
            curNode = slow.next;
            pre = null;
            while(curNode != null){
                ListNode nextNode = curNode.next;
                curNode.next = pre;
                pre = curNode;
                curNode = nextNode;
            }
            slow.next = pre;
            return true;
        }
    }
    

      

  • 相关阅读:
    用户组
    Compose
    ubuntu下不同版本python安装pip及pip的使用
    rest-framework-@action()装饰器
    数据库数据导出CSV文件,浏览器下载
    爬取拉钩网信息
    CSV模块
    DOM对象之查找标签&属性操作
    Java内存模型 一
    SQL优化之一
  • 原文地址:https://www.cnblogs.com/lyuwalle/p/13863960.html
Copyright © 2011-2022 走看看