首页 > 其他 > 详细

Leetcode47: Palindrome Linked List

时间:2015-07-13 18:44:33      阅读:96      评论:0      收藏:0      [点我收藏+]

Given a singly linked list, determine if it is a palindrome.

判断一个链表是不是回文的,一个比较简单的办法是把链表每个结点的值存在vector里,然后首尾比较,时间复杂度O(n),空间复杂度O(n)。

/**
 * 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> temp;
        ListNode* ptr = head;
        while(ptr!=NULL)
        {
            temp.push_back(ptr->val);
            ptr = ptr->next;
        }
        int n = temp.size();
        for(int i = 0; i < n/2; i++)
        {
            if(temp[i] != temp[n-1-i])
                return false;
        }
        return true;
    }
};
技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

Leetcode47: Palindrome Linked List

原文:http://blog.csdn.net/u013089961/article/details/46864145

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!