zoukankan      html  css  js  c++  java
  • Leetcode47: Palindrome Linked List

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

  • 相关阅读:
    mac pro发热发热发热
    从零开始搭建Vue组件库
    Charles模拟弱网测试
    webpack
    异步加载脚本
    Angular
    JavaScript模板语言
    Node.js
    gulp
    jsonp原理
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6962504.html
Copyright © 2011-2022 走看看