leetcode - 234. 回文链表

234. 回文链表

public boolean isPalindrome(ListNode head) {
            return twoPoint(head);
            //return withStack(head);
        }

        //找中点, 反转后一部分链表
        public boolean twoPoint(ListNode head) {
            //得中点
            ListNode mid = getMid(head);
            //得到反转的头, 从中点下一个开始反转链表
            ListNode reverseHead = reverse(mid.next);
            //让反转的头和尾一起移动看看是不是回文
            while (head != null && reverseHead != null) {
                if(head.val != reverseHead.val){
                    return false;
                }
                head = head.next;
                reverseHead = reverseHead.next;
            }
            //还原链表
            mid.next = reverse(reverseHead);
            return true;
        }

        //快慢指针得中点
        public ListNode getMid(ListNode head) {
            if (head == null || head.next == null || head.next.next == null) {
                return head;
            }
            ListNode slow = head.next;
            ListNode fast = head.next.next;
            while (fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            return slow;
        }

        //反转列表
        public ListNode reverse(ListNode head) {
            if (head == null) {
                return null;
            }
            ListNode cur = head;
            ListNode pre = null;
            while (cur != null) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }

        //使用栈迭代
        public boolean withStack(ListNode head){
            if(head == null){
                return false;
            }
            //把所有的node全都加到栈里
            Deque<Integer> stack = new LinkedList<>();
            ListNode cur = head;
            while(cur != null){
                stack.push(cur.val);
                cur = cur.next;
            }
            //逐个弹出跟链表当前节点的val对比
            ListNode compare = head;
            while(compare != null){
                if(stack.pop() != compare.val){
                    return false;
                }
                compare = compare.next;
            }
            return true;
        }

 

posted on 2022-11-03 16:47  老菜农  阅读(17)  评论(0编辑  收藏  举报

导航