LeetCode 234. Palindrome Linked List

234. Palindrome Linked List(回文链表)

链接

https://leetcode-cn.com/problems/palindrome-linked-list

题目

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

思路

题目不是很难,但是要是用各种方法可能会出不少问题。
我用的方法是最简单的把数字放到数组当中,然后头尾双指针比较,相同即为回文。
但是中间转换的时候可能出了些问题,只支持-128到127的(谁家int这么小),之后用equals又莫名其妙对了。

代码

  public class ListNode {

    int val;
    ListNode next;

    ListNode(int x) {
      val = x;
    }
  }

  public boolean isPalindrome(ListNode head) {
    List<Integer> list = new ArrayList<Integer>();
    while (head != null) {
      list.add(head.val);
      head = head.next;
    }
    int len = list.size();
    Integer[] num = list.toArray(new Integer [len]);
    for (int i = 0; i <= len / 2; i++) {
      if (!num[i].equals(num[len - 1 - i])) {
        return false;
      }
    }
    return true;
  }
posted @ 2020-03-18 13:51  cheng102e  阅读(81)  评论(0编辑  收藏  举报