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?

思路:

1.有大概两种思路,第一种将linkedLIst表中的数据读取到一个ArrayList中,然后从ArrayList前后开始比较即可。Time:O(n),Space:O(n)

2.第二种用快慢指针找到中间节点,然后将链表断成两个表,并将后面的链表逆转,然后顺序比较两个链表即可。Time:O(n),Space:O(1)

3.显然只有第二种方法符合题意。

代码:

public boolean isPalindrome(ListNode head) {
        if(head==null||head.next==null)
            return true;
        ListNode p=head,temp=head,quick=head;
        while(temp!=null&&quick!=null)
        {
            temp=temp.next;
            if(quick.next==null)
                break;
            quick=quick.next.next;
        }
        temp=reverseList(temp);
        p=head;
        while(temp!=null&&p!=null)
        {
            if(temp.val!=p.val)
                return false;
            temp=temp.next;
            p=p.next;
        }
        return true;
    }
    public ListNode reverseList(ListNode head)
    {
        ListNode tempHead=new ListNode(-1);
        ListNode p=head.next,q=null;
        tempHead.next=head;
        head.next=null;
        while(p!=null)
        {
            q=p;
            p=p.next;
            q.next=tempHead.next;
            tempHead.next=q;
        }
        return tempHead.next;
    }




你可能感兴趣的:(LeetCode,li,linked,palindrome)