回文链表判断(leetcode234)

2018-11-13  本文已影响0人  zhouwaiqiang

题目

解析方法

源代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        if (fast != null) slow = slow.next;//奇数需要走到下一个才是后半部分的开头
        slow = reverse(slow);//将后半段列表反转
        while (slow != null && slow.val == head.val) {
            slow = slow.next;
            head = head.next;
        }
        return slow == null;
    }
    
    //反转方法1头插法,开销比较大
    private ListNode reverse(ListNode head) {
        ListNode front = new ListNode(0);
        while (head != null) {
            ListNode temp = head;
            head = head.next;
            temp.next = front.next;
            front.next = temp;
        }
        return front.next;
    }
    //反转方法二
    private ListNode reverse1(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

代码分析

上一篇下一篇

猜你喜欢

热点阅读