关于leetcode个人解题总结:刷题15回文链表

2次阅读

共计 401 个字符,预计需要花费 2 分钟才能阅读完成。

Leetcode:234. 回文链表

解法: 先把链表中的元素值放入 arrayList 中,再判断 arrayList 的值是否回文来判断是否为回文链表。留神:不要把元素值放入 int[] 类型的数组,因为须要计算链表长度能力确定要开拓多大的 int 空间,消耗性能。

class Solution {public boolean isPalindrome(ListNode head) {ArrayList<Integer> arr = new ArrayList<Integer>();
        while(head != null){arr.add(head.val);
            head = head.next;
        }
        int first = 0;
        int last = arr.size() -1;
        while(first <= last){if(arr.get(first) != arr.get(last)) return false;
            first++;
            last--;
        }
        return true;
    }
}
正文完
 0