zoukankan      html  css  js  c++  java
  • LeetCode Palindrome LinkList

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

    该题是判断一个链表是不是回文链表。

    思路一:将该链表反转,然后从头开始对比节点值,时间复杂度O(n),空间复杂度O(N)

    思路二:利用runner pointer。很多的题目都可以利用这个方法来解决。Runner pointer和递归是解决链表问题最常用的两个方法。

    定义两个指针,slow runner和fast runner,fast以2倍于slow的速度向链表尾部移动。如有奇数个节点:当fast到达链表尾部时,slow恰好到达链表中间。如有偶数个节点:fast第一次为null时,slow恰好完成了一半节点的访问。把slow访问过的节点元素值压入一个stack里。此后slow继续向链表尾部访问,同时stack里的元素开始出栈(奇数个元素的情况下要跳过中间元素),比较两个元素值,一旦出现不等,则不是回文,否则是。该解法的时间复杂度是O(N),因为需要一次迭代,同时需要O(N)的空间用作stack来存放链表元素。

    下面是这两种方法的实现

    思路一:

    思路二:

        public boolean isPalindrome(ListNode head) {
            if(head==null)
                return true;
            if(head!=null && head.next==null)
                return true;
            ListNode slow=head;
            ListNode fast=head;
            boolean skip=false;
            Stack<Integer> stack=new Stack<Integer>();
            while(slow!=null)
            {
                if(fast==null)//偶数个
                {
                    skip=true;
                    if(slow.val!=stack.pop())
                        return false;
                }
                if(fast!=null && fast.next==null)//奇数个
                {
                    if(!skip)
                        slow=slow.next;
                    skip=true;
                    if(slow.val!=stack.pop())
                        return false;
                }
                if(!skip)
                    stack.push(slow.val);
                slow=slow.next;
                if(fast!=null && fast.next!=null)
                {
                    fast=fast.next.next;
                }
            }
            return true;
        }
  • 相关阅读:
    D. Babaei and Birthday Cake--- Codeforces Round #343 (Div. 2)
    Vijos P1389婚礼上的小杉
    AIM Tech Round (Div. 2) C. Graph and String
    HDU 5627Clarke and MST
    bzoj 3332 旧试题
    codeforces 842C Ilya And The Tree
    codesforces 671D Roads in Yusland
    Travelling
    codeforces 606C Sorting Railway Cars
    codeforces 651C Watchmen
  • 原文地址:https://www.cnblogs.com/maydow/p/4637177.html
Copyright © 2011-2022 走看看