LeetCode-234. 回文链表-Java实现

mac2025-09-12  6

题目

运行结果: 代码:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public boolean isPalindrome(ListNode head) { if(head==null){ return true; } ListNode headSlow = head; ListNode slow = head; if(head.next==null){ return true; } ListNode headQuick =head.next; ListNode quick = head.next; if(head.next.next==null){ return head.next.val==head.val; } boolean needSlowMove = false; while(true){ if(quick.next ==null){ break; } slow = slow.next; if(quick.next.next==null){ needSlowMove = true; break; } quick = quick.next.next; } //加入slow反转 headQuick = slow.next; ListNode headTemp = headSlow.next; boolean needExit = false; while(true){ if(headTemp == slow){ if(needSlowMove){ break; } needExit = true; } ListNode temp = headTemp; headTemp = temp.next; temp.next = headSlow; headSlow = temp; if(needExit){ break; } } head.next = null; while(true){ if(headQuick.val != headSlow.val){ return false; } if(headQuick.next==null){ if(headSlow.next==null){ return true; }else{ return false; } } if(headSlow.next == null){ if(headQuick.next==null){ return true; } return false; } headQuick = headQuick.next; headSlow = headSlow.next; } } }

思路

很简单,先用快慢指针找到中点,然后将前半部分进行反转得到一个新的链表,这样,前面反转后的链表和后面的链表一一比较就可以了。

最新回复(0)