LeetCode-Linked List-234-E:回文链表


请判断一个链表是否为回文链表。(对称链表)

思路

(1)借助了一个数组ArrayList,遍历存储链表的结点,然后再去两边同时取值比较。
(2)进阶:用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题。

解法1

class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null){
            return true;
        }
        
        ListNode node =head;
        ArrayList<ListNode> list = new ArrayList<>();

        while(node != null){
            list.add(node);
            node = node.next;
        }
        int len = list.size();
        int i = 0;
        int j = len-1;
        while(list.get(i).val == list.get(j).val){
            i++;
            j--;
            if(i==j || i>j){
                return true;
            }
        }

        return false;
    }
}

解法2-进阶

wait

发布了71 篇原创文章 · 获赞 16 · 访问量 1698

猜你喜欢

转载自blog.csdn.net/Xjheroin/article/details/104024485