美文网首页
234. Palindrome Linked List

234. Palindrome Linked List

作者: SilentDawn | 来源:发表于2018-08-17 15:02 被阅读0次

    Problem

    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?

    Example

    Input: 1->2
    Output: false
    
    Input: 1->2->2->1
    Output: true
    

    Code

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    static int var = [](){
        std::ios::sync_with_stdio(false);
        cin.tie(NULL);
        return 0;
    }();
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if(head==NULL)
                return true;
            ListNode *fast=head;
            ListNode *slow=head;
            ListNode *reverse=NULL;  
            while(fast->next!=NULL && fast->next->next!=NULL){
                fast = fast->next->next;
                ListNode *temp = slow;
                slow = slow->next;
                temp->next = reverse;
                reverse = temp;
            }
            if(fast->next==NULL){
                slow = slow->next;
            }else{
                ListNode *temp = slow;
                slow = slow->next;
                temp->next = reverse;
                reverse = temp; 
            }
            while(slow){
                if(slow->val!=reverse->val)
                    return false;
                slow=slow->next;
                reverse=reverse->next;
            }
            return true;
        }
    };
    

    Result

    234. Palindrome Linked List.png

    相关文章

      网友评论

          本文标题:234. Palindrome Linked List

          本文链接:https://www.haomeiwen.com/subject/dcttiftx.html