LeetCode-Palindrome Linked List

作者: Kindem | 来源:发表于2018-05-01 13:11 被阅读1次

    发布自Kindem的博客,欢迎大家转载,但是要注意注明出处

    问题

    请检查一个链表是否为回文链表。

    解答

    • 将链表存入线性表中然后直接对半验证

    java代码:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            List<Integer> list = new ArrayList<>();
            while (head != null) {
                list.add(head.val);
                head = head.next;
            }
            for (int i = 0; i < list.size() / 2; i++) {
                if (!list.get(i).equals(list.get(list.size() - i - 1))) return false;
            }
            return true;
        }
    }
    

    相关文章

      网友评论

        本文标题:LeetCode-Palindrome Linked List

        本文链接:https://www.haomeiwen.com/subject/rxbxrftx.html