题目描述
给定一个链表,请判断该链表是否为回文结构。
示例1:
输入: [1,2,2,1]
输出: true
备注: 1≤n≤1061 \leq n \leq 10^61≤n≤106
CODE
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 hereif (head == null || head.next == null) {return true;}List<Integer> vals = new ArrayList();while (head != null) {vals.add(head.val);head = head.next;}int i = 0;int j = vals.size() - 1;while (i < j) {if (!vals.get(i).equals(vals.get(j))) {return false;}i++;j--;}return true;}
}
思想
- (简单粗暴)首先,回文特点前后对阵;然后,遍历链表获取各节点val;最后,判断此val数组是否是回文即可