您的位置:首页 > 其它

Easy-题目54:234. Palindrome Linked List

2016-05-30 20:52 344 查看
题目原文:

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%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: