您的位置:首页 > 其它

【leetcode每日一题】234.Palindrome Linked List

2015-09-01 12:32 309 查看
题目:

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?

解析:

方法一:如果不考虑空间复杂度,则可以直接用vector来做。将所有节点压入vector,然后对比vector前半部分和后半部分。代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> result;
        while(head!=NULL)
        {
            result.push_back(head->val);
            head=head->next;
        }
        for(int i=0,j=result.size()-1;i<j;i++,j--)
        {
            if(result[i]!=result[j])
                return false;
        }
        return true;
    }
};
方法二:如果不占用额外的空间,我们可以将链表的后半部分逆序,然后再比较两部分是否相等。代码如下:

/**
 * 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)
    {
        if(head==NULL || head->next==NULL)
        {
            return head;
        }
        ListNode *curNode=head,*nextNode=head,*temp;
        while(nextNode!=NULL)
        {
            temp=nextNode->next;
            nextNode->next=curNode;
            curNode=nextNode;
            nextNode=temp;
        }
        head->next=NULL;
        head=curNode;
        return head;
    }
    bool isPalindrome(ListNode* head) {
        ListNode *fast=head,*slow=head,*tail;
        while(fast!=NULL && fast->next!=NULL)
        {
            tail=slow;
            fast=fast->next->next;
            slow=slow->next;
        }
        tail->next=NULL;
        ListNode *result=reverse(slow);
        ListNode *first=head,*second=result;
        while(first!=NULL)
        {
            if(first->val!=second->val)
            {
                return false;
            }
            first=first->next;
            second=second->next;
        }
        return true;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: