234. 回文链表
2023/10/27小于 1 分钟
234. 回文链表
简单解法一:链表值移至数组
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode currentNode = head;
while (currentNode != null) {
vals.add(currentNode.val);
currentNode = currentNode.next;
}
// 使用双指针判断是否回文
int front = 0;
int back = vals.size() - 1;
while (front < back) {
if (!vals.get(front).equals(vals.get(back))) {
return false;
}
front++;
back--;
}
return true;
}
}解法二:快慢指针
链表后半部分可以使用反转链表
Java
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
LinkedList<Integer> list = new LinkedList<>();
while (fast.next != null && fast.next.next != null){
list.add(slow.val);
slow = slow.next;
fast = fast.next.next;
}
if(fast.next != null) list.add(slow.val);
slow = slow.next;
while (slow != null) {
if(list.get(list.size() - 1) != slow.val) return false;
list.remove(list.size() - 1);
slow = slow.next;
}
return true;
}
}Python
class Solution:
# 876. 链表的中间结点
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
# 206. 反转链表
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre, cur = None, head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
def isPalindrome(self, head: Optional[ListNode]) -> bool:
mid = self.middleNode(head)
head2 = self.reverseList(mid)
while head2:
if head.val != head2.val: # 不是回文链表
return False
head = head.next
head2 = head2.next
return True