LeetCode(55)- Palindrome Linked List

题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:

思路:

  • 题意:判断一个链表是不是回文
  • 利用两个指针,一个快fast,一个慢slow,slow = head,fast = head,每次fast跳两格,slow一格,直到fast.next.next == null结束,slow位于中间,把slow.next往后的元素倒叙。prev = head,比较head和end的val

代码:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null){
            return true;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next !=null && fast.next.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode first = slow.next;
        if(first == null){
            return true;
        }
        ListNode sed =  first.next;
        ListNode thd = null;
        first.next = null;
        while(sed != null){
            thd = sed.next;
            sed.next = first;
            first = sed;
            sed = thd;
        }
        ListNode prev = head;
        while(prev != null && first != null){
            if(prev.val != first.val)return false;
            prev = prev.next;
            first = first.next;
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode,算法,面试,LinkedList,palindrome)