Easy-题目54:234. Palindrome Linked List

原创 2016年05月30日 20:52:31

题目原文:
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%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

234. Palindrome Linked List [easy] (Python)

题目链接https://leetcode.com/problems/palindrome-linked-list/题目原文 Given a singly linked list, determin...

LeetCode-Easy部分标签为LinkedList 234. Palindrome Linked List

根据回文数定义和单链表特点,求单链表是否为回文链表。要求时间复杂度O(n),空间复杂度O(1)。 思路,将后半部分反转,与前半部分元素一一比较。

234. Palindrome Linked List (Easy)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n)...

234. Palindrome Linked List(Linked List-Easy)

Given a singly linked list, determine if it is a palindrome. Follow up:Could you do it in O(n) time ...

234. Palindrome Linked List(python)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ti...

[LeetCode-234] Palindrome Linked List(回文链表、链表中间节点查找)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) tim...

LeetCode 234: Palindrome Linked List (回文链表)

Given a singly linked list, determine if it is a palindrome.Follow up:Could you do it in O(n) time a...

Leetcode 234. Palindrome Linked List

234. Palindrome Linked List Total Accepted: 69120 Total Submissions: 225579 Difficulty: Easy ...

(LeetCode 234)Palindrome Linked List

Leetcode第234题目是Palindrome Linked List。题目的描述如下: Given a singly linked list, determine if it is a pali...

234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)