zoukankan      html  css  js  c++  java
  • LeetCode——Palindrome Linked List

    Description:

    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(n)。竟然能过。。。。。。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode l;
        
        public boolean isPalindrome(ListNode head) {
            if(head == null || head.next == null) {
                return true;
            }
            
            List<Integer> nodeList = new ArrayList<>();
            ListNode it = head;
            while(it!=null) {
                nodeList.add(it.val);
                it = it.next;
            }
            boolean res = true;
            for(int i=nodeList.size()-1; i>=nodeList.size()/2; i--) {
                if(nodeList.get(i)!=head.val) {
                    res = false;
                    break;
                }
                else {
                    head = head.next;
                }
            }
            
            return res;
            
        }
        
    }
    

      想了想既然这样不如用递归,递归和栈类似,遍历两遍就OK,但是但是没想错的话空间复杂度还是O(n)吧,虽然没有显示的来new出空间。

          要想空间复杂度为O(1)现在能想到的只有找到链表中点,就地逆置单链表了。

  • 相关阅读:
    每种特定的迭代器如何使用
    常量迭代器
    容器迭代器
    三十分钟掌握STL
    高快省的排序算法
    FloatTest32 Example
    /浮点数的比较
    java第一天
    ACwing 898
    POJ 3268
  • 原文地址:https://www.cnblogs.com/wxisme/p/4725974.html
Copyright © 2011-2022 走看看