Easy-题目54:234. Palindrome Linked List

来源:互联网 发布:弹弹安卓版吉他软件 编辑:程序博客网 时间:2024/06/05 19:05

题目原文:
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?
题目大意:
给一个单链表,判断它是不是回文的。
你能实现O(n)时间复杂度和O(1)空间复杂度吗?
题目分析:
如果用O(1)空间复杂度的话,可以求出链表的中点,然后翻转前半个链表再比较两个“半链表”是否相同。但是,我觉得代码太麻烦,就改用O(n)的空间复杂度了,这样的算法很简单:把链表转换成线性表,因为是随机存储的很容易判断是否是回文。
源码:(language:cpp)

class Solution {public:    bool isPalindrome(ListNode* head) {        int length=0;        for(ListNode* p=head;p;p=p->next,length++);//length is the length of linklist        int* array=new int[length];        int i=0;        for(ListNode* p=head;p;p=p->next)            array[i++]=p->val;        return isPalindromeArray(array,length);    }    bool isPalindromeArray(int* array,int length)    {        if(length==0||length==1)             return true;        else if(*array!=*(array+length-1))            return false;        else            return isPalindromeArray(array+1,length-2);    }};

成绩:
28ms,beats 9.66%,众数28ms,58.57%

0 0
原创粉丝点击