(链表)13-判断一个链表是否为回文结构

发布时间 2023-11-15 22:52:24作者: StringBuilder

 1 import java.util.*;
 2 
 3 /*
 4  * public class ListNode {
 5  *   int val;
 6  *   ListNode next = null;
 7  * }
 8  */
 9 public class Solution {
10     /**
11      *
12      * @param head ListNode类 the head
13      * @return bool布尔型
14      */
15     public boolean isPail (ListNode head) {
16         // 申请一个数组存储链表中的数据
17         ArrayList<Integer> nums = new ArrayList();
18         // 将链表元素取出依次放入数组
19         while (head != null) {
20             nums.add(head.val);
21             head = head.next;
22         }
23         // 申请头尾两个指针-从头尾同时访问数组
24         int left = 0;
25         int right = nums.size() - 1;
26         while (left < right) {
27             if (nums.get(left).equals(nums.get(right)) == false) {
28                 // 左右不对称
29                 return false;
30             }
31             // 移动指针
32             left = left + 1;
33             right = right - 1;
34         }
35         // 校验完毕-左右对称
36         return true;
37     }
38 }