回文链表空间复杂度O(1)解法

This commit is contained in:
linlihong 2024-08-21 11:46:04 +08:00
parent 8000e4b1fa
commit 1f28fb2d4c
1 changed files with 53 additions and 13 deletions

View File

@ -1,5 +1,7 @@
package com.cool.hot100.linkedlist; package com.cool.hot100.linkedlist;
import org.junit.Test;
public class Num234 { public class Num234 {
/** /**
@ -12,8 +14,37 @@ public class Num234 {
public ListNode node; public ListNode node;
public boolean isPalindrome(ListNode head) { public boolean isPalindrome(ListNode head) {
node = head; // node = head;
return reNodeCheck(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;
}
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;
} }
//递归反向对比 //递归反向对比
@ -29,5 +60,14 @@ public class Num234 {
} }
return true; 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);
}
} }