234. Palindrome Linked List - Easy
前往題目
想法
- 因為是單鏈,所以只能先找中間點,不然沒有基準
- 找到中間點後就可以知道左半部和右半部的分水嶺
- 沒想到可以
Reverse
思路
- 找到中間點
- 反轉右半邊
- 檢查
palindrome
反轉那邊有點繞,但基本上就是
- 定義一個
previous
指針,然後會從slow
指針開始反轉(因為他一定在mid+1
) - 存
slow.next
,也就是原來的下一個 slow.next
換成previous
,這裡就反轉了順序- 然後
previous
變成slow
,因為要繼續往右反轉 - 而
slow
變成他原來的下一個,也是為了要往右反轉,等於說每輪的最後slow
和previous
都要往右一個位置,因為要換下一組反轉
Code
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode slow, fast;
slow = fast = head;
// Find mid point
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Odd length of the list
if (fast != null) slow = slow.next;
// Reverse the second part of the list
ListNode prev = null;
while (slow != null) {
// Store the next
ListNode next = slow.next;
// Reverse the next of the slow pointer to point the prev
slow.next = prev;
// Previous becomes the slow
prev = slow;
// Move slow pointer to reverse other nodes
slow = next;
}
ListNode left = head, right = prev;
// Check palindrome
while (right != null) {
// Mismatch
if (right.val != left.val) return false;
// Move pointers
left = left.next;
right = right.next;
}
return true;
}
}
2024/10/04
- Reverse的時候處理有bug
234. Palindrome Linked List - Easy
https://f88083.github.io/2024/01/09/234-Palindrome-Linked-List-Easy/