Java题解 | 判断链表是否回文(转化为数组处理)
判断一个链表是否为回文结构
http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
一拿到这个题,我第一感觉就是首尾双指针,遍历比较,但是链表中往回走不太好走,如果是数组就非常简单。我便想到可以将链表转化为数组,再使用双指针遍历,那么就非常简单了。
思路:
1.先获取到链表的长度
2.创建数组,再次遍历链表将链表中的值依次存放到数组
3.创建双指针首尾比较数组
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 the head * @return bool布尔型 */ public boolean isPail (ListNode head) { // write code here ListNode target = head; int len = 1; //遍历一次链表求出链表长度 while(target.next != null){ target = target.next; len++; } int[] arr = new int[len]; //遍历链表将链表的值放入数组中 for(int i = 0; i < len; i++){ arr[i] = head.val; if(head.next != null){ head = head.next; } } //创建指针处理数组 int left = 0; int right = len - 1; while(left <= right){ if(arr[left] == arr[right]){ left++; right--; }else{ //如果首尾比较不相等,则直接返回为false return false; } } //如果成功跳出循环,说明链表是回文结构 return true; } }