题目
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
示例 1:
输入:head = [1,2,2,1] 输出:true
示例 2:
输入:head = [1,2] 输出:false
提示:
- 链表中节点数目在范围
[1, 105]
内 0 <= Node.val <= 9
解答
源代码
/**
* 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) {
ListNode halfList = getHalfList(head);
System.out.println(halfList.val);
ListNode reversedList = reverse(halfList);
System.out.println(reversedList.val);
while (reversedList != null) {
if (head.val != reversedList.val) {
return false;
}
reversedList = reversedList.next;
head = head.next;
}
return true;
}
public ListNode getHalfList(ListNode head) {
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
总结
这道题和之前的 143.重排链表 很类似,先找到中间节点,将后半部分链表反转,重排链表需要交替进行连接,这道题需要比较每个节点的值。