234. 回文链表
题目:
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例1:
输出true
示例2:
输出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) {ListNode mid = middleNode(head);ListNode p = reverseList(mid.next);ListNode q = head;while(p != null){if(p.val != q.val){return false;}p = p.next;q = q.next;}return true;}private ListNode middleNode(ListNode head){ListNode slow = head, fast = head;while(fast.next != null && fast.next.next != null){slow = slow.next;fast = fast.next.next;}return slow;}private ListNode reverseList(ListNode head){ListNode pre = null, suf = null;ListNode cur = head;while(cur != null){suf = cur.next;cur.next = pre;pre = cur;cur = suf;}return pre;}
}