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

来源:互联网 发布:阿里云怎么安装软件 编辑:程序博客网 时间:2024/06/05 03:44
题目:

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;    }};



0 0
原创粉丝点击