题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
将链表值存入数组,双指针判断是否为回文结构
public class Solution { /** * * @param head ListNode类 the head * @return bool布尔型 */ public boolean isPail (ListNode head) { // write code here ListNode temp = head; int len = 0; while(temp != null){ len++; temp = temp.next; } // 创建和链表长度相同的数组,并将链表值存入数组 int[] res = new int[len]; for(int i = 0; i < len; i++){ res[i] = head.val; head = head.next; } // 双指针判断是否是回文结构 int left = 0, right = len - 1; while(left < right){ if(res[left] != res[right]){ return false; } left++; right--; } return true; } }