234.回文链表Java
题目描述
请判断一个链表是否为回文链表。
输入输出样式
示例1:
输入: 1->2
输出: false
示例2:
输入: 1->2->2->1
输出: true
本题来自LeetCode:https://leetcode-cn.com/problems/palindrome-linked-list/
思路
首先使用快慢指针找到链表的中间,然后把后面一半链表反转指向,将前一半链表和后一半链表对比是否相同即可。
快慢指针:fast,slow两个指针一个一次走两个节点,一个一次走一个。这样当快的走到尾部,相当于fast的路程是slow的两倍,因为fast的速度是slow的两倍。slow也就是链表中间
算法分析
时间复杂度O(n),空间复杂度为O(1)
求解函数
/**
* 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 fast = head, slow = head;
//快慢指针
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//如果fast不是空那说明节点总数为奇数个,所以slow需要后移一位
if (fast != null) {
slow = slow.next;
}
//迭代法反转链表
ListNode pre = null, cur = slow;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
//对比前后两部分
fast = head;
slow = pre;
while (slow != null) {
if (fast.val != slow.val) return false;
fast = fast.next;
slow = slow.next;
}
return true;
}
}