LeetCode234-回文链表
非商业,LeetCode链接附上:
https://leetcode-cn.com/problems/palindrome-linked-list/
进入正题。
题目:
请判断一个链表是否为回文链表。
(进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?)
示例:
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
代码实现:
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
//快慢指针,找到链表的中点
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//将slow之后的链表反转
while (slow != null) {
ListNode next = slow.next;
slow.next = pre;
pre = slow;
slow = next;
}
while (head != null && pre != null) {
if(head.val != pre.val) return false;
head = head.next;
pre = pre.next;
}
return true;
}
//时间复杂度O(n),空间复杂度O(1)
分析:
首先明确什么是回文链表,根据回文链表的性质确定可以用“快慢指针”的方式进行解题。
针对链表的问题,一个需要注意的点就是节点的null判断,null基本是作为问题的边界(终止条件)。
--End

浙公网安备 33010602011771号