LeetCode-Palindrome Linked List

Posted IncredibleThings

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Palindrome Linked List相关的知识,希望对你有一定的参考价值。

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

Follow up:
Could you do it in O(n) time and O(1) space?
/**
 * 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 mid=findMiddle(head);
        mid.next=reverse(mid.next);
        ListNode p1=head, p2=mid.next;
        while(p2 != null && p1 != null && p1.val == p2.val){
            p1=p1.next;
            p2=p2.next;
        }
        if(p2 == null){
            return true;
        }
        else{
            return false;
        }
        
    }
    public ListNode findMiddle(ListNode head){
        if(head ==null){
            return null;
        }
        ListNode slow=head, fast=head.next;
        while(fast != null && fast.next !=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        return slow;
    }
    public ListNode reverse(ListNode head){
        ListNode prev=null;
        while(head != null){
            ListNode temp=head.next;
            head.next=prev;
            prev=head;
            head=temp;
        }
        return prev;
    }
}

 

以上是关于LeetCode-Palindrome Linked List的主要内容,如果未能解决你的问题,请参考以下文章

shell中$(( )) 与 $( ) 还有${ }的区别

链表类算法题

LinkedHashSet

LinkedList的分析

LinkedHashSet

LinkedList 集合类