234. Palindrome Linked List

2018/04/20 leetcode 共 670 字,约 2 分钟

Title

the problem link

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?

反转链表,优化不够,只是反转后对比

Solution

//cpp:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* Reverse(ListNode* head){
        ListNode *p1=NULL;
        
        while(head){
            ListNode *p=new ListNode(head->val);
            p->next=p1;
            p1=p;
            head=head->next;
        }
        return p1;
    }
    bool isPalindrome(ListNode* head) {
        ListNode* root=head;
        ListNode* root1=Reverse(head);
        while(root1&&root&&root1->val==root->val){
            root1=root1->next;
            root=root->next;
        }
        if(!root1&&!root){
            return true;
        }else{
            return false;
        }
    }
    
};

Search

    Table of Contents