leetcode-palindrome-linked-list

题目大意

  https://leetcode.com/problems/palindrome-linked-list/

  判断单链表是否是回文,要求时间复杂度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
45
46
47
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
int len = 0;
ListNode tHead = head;
while (tHead != null) {
len++;
tHead = tHead.next;
}
int l = len / 2;
// 将前l长度的链表就地逆置
ListNode cur = head;
ListNode pre = null;
for (int i = 0; i < l; i++) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
ListNode p1 = pre;
ListNode p2 = null;
if (len % 2 == 0) {
p2 = cur;
} else {
p2 = cur.next;
}
while (p1 != null) {
if (p1.val != p2.val) {
return false;
} else {
p1 = p1.next;
p2 = p2.next;
}
}
return true;
}
}