题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
思路
1. 辅助数组法
图片来源:https://leetcode-cn.com/problems/palindrome-linked-list/solution/hui-wen-lian-biao-yuan-di-jian-cha-bu-yong-fan-zhu/
2. 反转链表 + 双指针
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode currentNode = head;
List<Integer> list = new ArrayList<>();
while(currentNode != null) {
list.add(currentNode.val);
currentNode = currentNode.next;
}
int left = 0, right = list.size() - 1;
while(left <= right) {
if(!list.get(left).equals(list.get(right))) return false;
left++;
right--;
}
return true;
}
}
class Solution {
public boolean isPalindrome(ListNode head) {
// 找到中点
// 反转后段部分
// left,right比较
// 找中点
if(head == null || head.next == null) return true;
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
// 反转后段部分
fast = reverse(slow);
// left, right判断
ListNode left = head, right = fast;
while(left != right) {
if(left.val != right.val) return false;
if(left.next == right) break;
left = left.next;
right = right.next;
}
reverse(fast);
return true;
}
private ListNode reverse(ListNode node) {
if(node == null || node.next == null) return node;
ListNode prevNode = null;
ListNode currNode = node;
while(currNode != null) {
ListNode tempNext = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = tempNext;
}
return prevNode;
}
}