LeetCode234. 迴文連結串列
阿新 • • 發佈:2020-12-15
思路:【快慢指標 + 反轉連結串列】通過快慢指標找到中間節點 ----> 切成兩個連結串列 ----> 對後半部分進行reverse操作 -----> 依次比較前部分和後部分的值
與LeetCode143. 重排連結串列解法類似。
class Solution { public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; ListNode fast = head, slow = head;while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } ListNode l2 = slow.next; slow.next = null; l2 = reverse(l2); while (head != null && l2 != null) { if (head.val != l2.val) {return false; } head = head.next; l2 = l2.next; } return true; } private ListNode reverse(ListNode head) { ListNode cur = head; ListNode pre = null, next = null; while (cur != null) { next = cur.next; cur.next= pre; pre = cur; cur = next; } return pre; } }