Leetcode 234、回文链表

Leetcode 234、回文链表

在这里插入图片描述

方法一、使用数组存储链表中的节点

思路:遍历链表,把链表中的值添加到list数组里面,然后使用双指针判断list数组是否是回文。
时间复杂度:O(N)
空间复杂度:O(N) 使用数组存储链表中的值

class Solution {
    /**
        快慢指针
     */
    public boolean isPalindrome(ListNode head) {
        if(head == null) return true;
        List<Integer> list = new ArrayList<>();

        while(head != null) {
            list.add(head.val);
            head = head.next;
        }

        int left = 0, right = list.size() - 1;
        while(left <= right) {
            if(list.get(left) != list.get(right)) {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }
}

方法二、快慢指针+栈

快慢指针,first指针移动一个位置,second移动两个位置;链表节点个数可能是奇数也可能是偶数;

  • 如果节点个数是奇数,跳出第一个循环,second.next为空,弹出栈顶元素,也就是链表中间的节点值;然后first继续向下遍历和statck中的元素进行比较;

  • 因为在遍历的时候,每次都把first指向的节点值入栈,所以跳出循环以后,要弹出栈顶元素;first继续向下遍历与stack栈顶元素进行比较。
    在这里插入图片描述

  • 如果节点个数是偶数,跳出循环以后second.next !=null,不需要弹出栈顶元素,直接进入第二个while循环进行判断
    在这里插入图片描述
    时间复杂度:O(N)
    空间复杂度:O(1)

class Solution {
    /**
        快慢指针
     */
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) return true;

        Deque<Integer> stack = new LinkedList<>();
        ListNode first = head;
        ListNode second = head;
        stack.push(first.val);

        while(second.next != null) {
            if(second.next.next != null) {
                first = first.next;
                stack.push(first.val);
                second = second.next.next;
            }else {
                break;
            }
        }

        if(second.next == null) {
            stack.pop();
        }

        while(first.next != null) {
            first = first.next;
            int curr = stack.pop();
            if(curr != first.val) {
                return false;
            }
        }

        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值