链表算法之【回文链表】
目录
LeetCode-234题
LeetCode-234题
给定一个单链表的头节点head,判断该链表是否为回文链表,是返回true,否则返回false
class Solution {/*** 这里的解题思路为:* (1)、找中间节点* (2)、反转链表* (3)、遍历比较节点值是否相等*/public boolean isPalindrome(ListNode head) {//checkif (head == null)return false;if (head.next == null)return true;//找中间节点(while结束后slow指针指向中间节点)ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}//反转(从slow开始的节点进行反转)ListNode reserve = null;ListNode p = slow;while (p != null) {ListNode tmp = p.next;p.next = reserve;reserve = p;p = tmp;}//比较是否回文(逐个比较节点值是否相同)while (head != null && reserve != null) {if (head.val != reserve.val)return false;head = head.next;reserve = reserve.next;}return true;}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}