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)现在能想到的只有找到链表中点,就地逆置单链表了。

  • 相关阅读:
    做统计图的好工具
    QueryBuildRange中的表达式
    四种方式话Equal
    QueryBuildRange的空值
    GetHashCode()初探
    X++中的字符串操作函数
    寻找缺陷的方法
    字程序级别的重构
    代码大全的方向
    多线程啊
  • 原文地址:https://www.cnblogs.com/wxisme/p/4725974.html
Copyright © 2011-2022 走看看