/**
* 判断是否为回文链表
*/
public class PalindromeList {
//回文链表 = 中间节点 + 链表转置(原地转置,将原链表进行倒置)
public boolean chkPalindrome(ListNode A){
//找到中间节点
ListNode middle = middleNode(A);
//倒置后半部分链表
ListNode B = reverse(middle);
while(A != null && B != null){
if(A.val != B.val){
return false;
}
A = A.next;
B = B.next;
}
return true;
}
//链表倒置(递归)
private ListNode reverse(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode tmpNext = head.next;
ListNode newHead = reverse(head.next);
tmpNext.next = head;
head.next = null;
return newHead;
}
//找中间节点,快慢指针
private ListNode middleNode(ListNode head) {
ListNode fast = head,slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
牛客网判断是否是回文链表(java)详细讲解
最新推荐文章于 2024-02-16 22:46:18 发布