首页 > 其他 > 详细

链表--回文链表(leetcode234

时间:2020-06-10 00:58:43      阅读:53      评论:0      收藏:0      [点我收藏+]

方法1:用一个辅助栈

把链表中所有元素存储到栈中,也就实现了将链表中的元素逆序存放到栈中。然后再将栈中元素一个一个出栈并和链表比对,将链表一个一个往下指

时空间复杂度:O(n)

    public static boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null){
            return true;
        }
        Stack<Integer> stack = new Stack<Integer> ();
        ListNode temp = head;
        while (temp != null){
            stack.push(temp.val);
            temp = temp.next;
        }
        while (head != null){
            if(stack.pop() != head.val){
                return false;
            }

            head = head.next;
        }

        return true;


    }

链表--回文链表(leetcode234

原文:https://www.cnblogs.com/swifthao/p/13081981.html

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