【双指针】234. 回文链表

234. 回文链表

解题思路

  • 首先找到链表中点
  • 然后将链表的后半部分进行翻转
  • 之后将链表前半部分和翻转的链表进行对比
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow,fast;
        slow = fast = head;
        // 快慢指针 找到链表中点
        // 如果链表的长度是奇数 那么slow会指向中间这个节点  但是为了进行对比 希望slow指向中间节点的
        // 下一个节点
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }


        if(fast != null){
            slow = slow.next;
        }

        ListNode left = head;
        ListNode right = reverse(slow);


        // 前后指针往中间对比
        while(right != null){
            if(left.val != right.val){
                return false;
            }
            left = left.next;
            right = right.next;
        }

        return true;
    }

    // 反转链表
    ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode cur = head;

        while(cur != null){
            // 提前保存好下一个节点
            ListNode next = cur.next;
            cur.next = pre;

            // 移动指针
            pre = cur;
            cur = next;
        }

        return pre;
    }
}

你可能感兴趣的:(#,Leetcode,链表,数据结构)