From 1f28fb2d4cd0edc8e2d4d472c897a818b600104d Mon Sep 17 00:00:00 2001 From: linlihong <747682928@qq.com> Date: Wed, 21 Aug 2024 11:46:04 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E6=96=87=E9=93=BE=E8=A1=A8=E7=A9=BA?= =?UTF-8?q?=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6O(1)=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cool/hot100/linkedlist/Num234.java | 66 +++++++++++++++---- 1 file changed, 53 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/cool/hot100/linkedlist/Num234.java b/src/main/java/com/cool/hot100/linkedlist/Num234.java index 9718f0e..c8f2839 100644 --- a/src/main/java/com/cool/hot100/linkedlist/Num234.java +++ b/src/main/java/com/cool/hot100/linkedlist/Num234.java @@ -1,5 +1,7 @@ package com.cool.hot100.linkedlist; +import org.junit.Test; + public class Num234 { /** @@ -12,22 +14,60 @@ public class Num234 { public ListNode node; public boolean isPalindrome(ListNode head) { - node = head; - return reNodeCheck(head); - } +// node = head; +// return reNodeCheck(head); + //时间复杂度为O(n),空间复杂度为O(1)解法 + ListNode slowNode = head; + ListNode fastNode = head; + while (fastNode.next != null && fastNode.next.next != null) { + fastNode = fastNode.next.next; + slowNode = slowNode.next; + } + ListNode temp = head; + ListNode reverse = reverse(slowNode.next); + while (reverse != null) { + if (reverse.val != temp.val) { + return false; + } + temp = temp.next; + reverse = reverse.next; - //递归反向对比 - public boolean reNodeCheck(ListNode node){ - if (node!=null){ - if(!reNodeCheck(node.next)){ - return false; - } - if(node.val!=this.node.val){ - return false; - } - this.node=this.node.next; } return true; } + public ListNode reverse(ListNode node) { + ListNode pre = null; + while (node != null) { + ListNode next = node.next; + node.next = pre; + pre = node; + node = next; + } + return pre; + } + + //递归反向对比 + public boolean reNodeCheck(ListNode node) { + if (node != null) { + if (!reNodeCheck(node.next)) { + return false; + } + if (node.val != this.node.val) { + return false; + } + this.node = this.node.next; + } + return true; + } + @Test + public void test(){ +// ListNode node=new ListNode(5,null); + ListNode node1=new ListNode(1,null); + ListNode node2=new ListNode(2,node1); + ListNode node3=new ListNode(2,node2); + ListNode node4=new ListNode(1,node3); + isPalindrome(node4); + } + }