From 301a8b39116187fe10351e9f302d94eef32691ba Mon Sep 17 00:00:00 2001 From: ehlxr Date: Sun, 4 Dec 2022 22:25:27 +0800 Subject: [PATCH] Palindrome Linked List --- .../algorithm/linkedlist/Palindrome.java | 90 ++++++++++++------- 1 file changed, 60 insertions(+), 30 deletions(-) diff --git a/budd-common/src/main/java/io/github/ehlxr/algorithm/linkedlist/Palindrome.java b/budd-common/src/main/java/io/github/ehlxr/algorithm/linkedlist/Palindrome.java index 7c58f0d..6fd4307 100644 --- a/budd-common/src/main/java/io/github/ehlxr/algorithm/linkedlist/Palindrome.java +++ b/budd-common/src/main/java/io/github/ehlxr/algorithm/linkedlist/Palindrome.java @@ -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); - } }