无论如何不要轻言放弃。力扣力扣:https://leetcode-cn.com/problems/palindrome-linked-list/
#234 回文链表
请判断一个链表是否为回文链表。
输入: 1->2 输出: false
输入: 1->2->2->1 输出: true
方法一:数组
将所有元素放到一个数组中,再利用双指针迭代比较元素中的内容
/**
* 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 || head.next == null){
return true;
}
java.util.ArrayList<Integer> arr = new java.util.ArrayList<Integer>();
// 申请一个容器,将元素放入数组
while(head!=null){
arr.add(head.val);
head = head.next;
}
int i = 0; // 头指针往后遍历
int j = arr.size() - 1; // 尾指针往前遍历
while(i < j){
if(arr.get(i).compareTo(arr.get(j))!=0){
return false;
}
++i;
--j;
}
return true;
}
}
方法二:双指针+反转
我们利用链表的两个操作:(1) 找到链表的中间节点 (2) 反转链表
通过这两个操作之后,原链表就以中间节点被一分为二; 前半部分一个链表,后半部分(被反转了)为一个链表
然后遍历这两个链表,如果遍历过程中发现两个链表节点不同,就说不是回文链表,直接返回false即可
如果链表遍历完了,说明是回文链表
注意一个小细节,如果链表长度是偶数的话,前半部分和后半部分长度是一样的
如果链表长度是奇数,那么前半部分的长度比后半部分长度多1个
所以最后迭代链表的时候,以后半部分为准就可以了,当链表总长为奇数时,前半部分的最后一个节点就不会被遍历到了
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
ListNode p = new ListNode(-1);
ListNode low = p;
ListNode fast = p;
p.next = head;
// 快慢指针迭代
while(fast != null && fast.next!=null){
low = low.next;
fast = fast.next.next;
}
ListNode cur = low.next;
ListNode pre = null;
low.next = null;
low = p.next;
// 将链表一分为二之后,反转链表后半部分
while(cur!=null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;cur = temp;
}
// 将链表前半部分和反转部分比较
while(pre != null){
if(low.val != pre.val){
return false;
}
low = low.next;
pre = pre.next;
}
return true;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var isPalindrome = function(head) {
let slow = head,fast = head;
while(fast && fast.next){
slow = slow.next;
fast = fast.next.next;
}
// 链表为奇数时slow还需要走一步
if(fast) slow = slow.next;
let left = head;
let right = reserve(slow);
while(right){
if(right.val !== left.val) return false;
right = right.next;
left = left.next;
}
return true;
};
// 反转链表
const reserve = function(head){
let pre = null,cur = head,next = head;
while(cur !== null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
};