無論如何不要輕言放棄。力扣力扣: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;
};