Rearch Interest: Visualization">
234. 回文链表
题目描述
请判断一个链表是否为回文链表。
示例 1: >输入: 1->2
>输出:
false
示例 2: >输入: 1->2->2->1
>输出:
true
进阶:
你能否用 \(O(n)\) 时间复杂度和 \(O(1)\) 空间复杂度解决此题?
我的代码
\(T(N) = O(N)\), \(S(N) = O(1)\)
{.line-numbers} 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
45
46
/**
* 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 MySolution234
{
public boolean isPalindrome(ListNode head)
{
if (head==null||head.next==null) return true;
if (head.next.next==null) return head.val==head.next.val;
ListNode p = head; int length = 0;
while (p!=null)
{
length++; p = p.next;
}
ListNode prev = head; ListNode post;
for (int i=0; i<length/2; i++)
prev = prev.next;
p = prev.next; post = p.next;
prev.next = null; p.next = prev;
while (post!=null)
{
prev = p;
p = post;
post = post.next;
p.next = prev;
}
ListNode pointer = head;
for (int i=0; i<length/2; i++)
{
if (p.val!=pointer.val) return false;
p = p.next; pointer = pointer.next;
}
return true;
}
}
1 | /** |
思路: 递归
\(T(N) = O(N)\), \(S(N) = O(N)\)
递归遍历节点的方式如下。
1 | function print_values_in_reverse(ListNode head) |
因此,如果我们能利用递归来反向遍历节点, 同时使用一个递归函数外面的变量向前迭代, 就可以判断链表是否为回文的。
代码
1 | class Solution234 |