题目描述:

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

示例:

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

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

解答代码:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public boolean isPalindrome(ListNode head) {
  13. ArrayList array = new ArrayList<Integer>();
  14. if (head == null) {
  15. return false;
  16. }
  17. while(head != null) {
  18. array.add(head.val);
  19. head = head.next;
  20. }
  21. int count = array.size();
  22. for (int i = 0; i < count; i ++) {
  23. if (array.get(i) != array.get(count -i - 1)) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. }

解答思路:

比较丑的解答方法,将链表赋值给顺序表,然后双指针比较。

运行结果

图片.png