题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//解法:
//1.通过快慢指针找到中间节点;
//2.从慢指针的下一个指针开始逆序;(这里必须是下一个开始)
//3.比较逆序后的链表和原来的链表
if(head == null || head.next == null) return true;
ListNode fast = head;
ListNode slow = head;
//1.找到中间节点slow
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
//从中间节点的下一个节点开始逆序
slow = slow.next;
ListNode reverse = null;
ListNode tmp = null;
//2.链表反转
while(slow != null){
tmp = slow.next;
slow.next = reverse;
reverse = slow;
slow = tmp;
}
//3.比较结果
while(reverse != null){
if(head.val != reverse.val){
return false;
}
head = head.next;
reverse = reverse.next;
}
return true;
}
}
网友评论