目錄
LeetCode-234題
LeetCode-234題
給定一個單鏈表的頭節點head,判斷該鏈表是否為回文鏈表,是返回true,否則返回false
class Solution {/*** 這里的解題思路為:* (1)、找中間節點* (2)、反轉鏈表* (3)、遍歷比較節點值是否相等*/public boolean isPalindrome(ListNode head) {//checkif (head == null)return false;if (head.next == null)return true;//找中間節點(while結束后slow指針指向中間節點)ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}//反轉(從slow開始的節點進行反轉)ListNode reserve = null;ListNode p = slow;while (p != null) {ListNode tmp = p.next;p.next = reserve;reserve = p;p = tmp;}//比較是否回文(逐個比較節點值是否相同)while (head != null && reserve != null) {if (head.val != reserve.val)return false;head = head.next;reserve = reserve.next;}return true;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}