Palindrome Linked List

master
ehlxr 2022-12-04 22:25:27 +08:00
parent ba50b612d8
commit 301a8b3911
1 changed files with 60 additions and 30 deletions

View File

@ -25,11 +25,70 @@
package io.github.ehlxr.algorithm.linkedlist;
/**
*
*
* @author ehlxr
* @since 2022-12-03 23:11.
*/
public class Palindrome {
public static class ListNode {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(1);
System.out.println(head);
System.out.println(isPalindrome(head));
head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(3);
head.next.next.next.next = new ListNode(2);
head.next.next.next.next.next = new ListNode(1);
System.out.println(head);
System.out.println(isPalindrome(head));
}
/**
* slow, fast slow fast fast slow
* head
*/
public static boolean isPalindrome(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head, fast = head, pre = null;
while (fast != null && fast.next != null) {
fast = fast.next.next;
ListNode tmp = slow.next;
slow.next = pre;
pre = slow;
slow = tmp;
// slow = slow.next;
}
if (fast != null) {
// 节点个数为奇数
slow = slow.next;
}
System.out.println("中间节点:" + slow);
System.out.println("中位点反转:" + pre);
while (pre != null) {
if (pre.val != slow.val) {
return false;
}
pre = pre.next;
slow = slow.next;
}
return true;
}
private static class ListNode {
int val;
ListNode next;
@ -53,33 +112,4 @@ public class Palindrome {
'}';
}
}
public static boolean isPalindrome(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
System.out.println("中位节点:" + slow);
return false;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// head.next.next.next.next.next = new ListNode(6);
System.out.println(head);
isPalindrome(head);
}
}