题目:234. 回文链表
给你一个单链表的头节点
head
,请你判断该链表是否为回文链表
。如果是,返回
true
;否则,返回false
。
解题思路
回文定义:是指正读和反读都相同的字符序列。
将链表数据获取出来,再通过前后指针向中间遍历,数据一致,则是回文;如果不一致则不是回文。
解题过程
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode currentNode = head;
while (currentNode != null) {
vals.add(currentNode.val);
currentNode = currentNode.next;
}
// 使用双指针判断是否回文
int front = 0;
int back = vals.size() - 1;
while (front < back) {
if (!vals.get(front).equals(vals.get(back))) {
return false;
}
front++;
back--;
}
return true;
}
}