回文链表

234. 回文链表

给你一个单链表的头节点 head ,请你判断该链表是否为

回文链表

。如果是,返回 true ;否则,返回 false

示例 1:

img

1
2
输入:head = [1,2,2,1]
输出:true

示例 2:

img

1
2
输入:head = [1,2]
输出:false

提示:

  • 链表中节点数目在范围[1, 105]
  • 0 <= Node.val <= 9

进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode pre = findMiddel(head);
pre.next = reverseList(pre.next);
ListNode l1 = head;
ListNode l2 = pre.next;
while(l2 != null){
if(l1.val != l2.val){
return false;
}
l1 = l1.next;
l2 = l2.next;
}
return true;

}

//找到链表中间的第一个节点
public ListNode findMiddel(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}

//反转链表
public ListNode reverseList(ListNode head){
ListNode pre = null;
ListNode p = head;
while(p != null){
ListNode q = p.next;
p.next = pre;
pre = p;
p = q;
}
return pre;
}
}

回文链表
http://example.com/2024/04/28/算法/链表/20. 回文链表/
作者
PALE13
发布于
2024年4月28日
许可协议