Palindrome Linked List

This commit is contained in:
ehlxr 2022-12-04 22:25:27 +08:00
parent ba50b612d8
commit 301a8b3911

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);
}
}