Keshawn_lu's Blog

Leetcode 234. 回文链表

字数统计: 351阅读时长: 1 min
2020/10/23 Share

题目简介:

请判断一个链表是否为回文链表。

示例 1:

1
2
输入: 1->2
输出: false

示例 2:

1
2
输入: 1->2->2->1
输出: true

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

思路:

  1. 找到中间结点(若长度为奇数,则返回第n/2 + 1个结点;若长度为偶数,则返回第n/2个结点)
  2. 切断前后两半,将后一半逆转
  3. 前后链表逐个进行比较,若最后前一半链表剩下的结点数不超过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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

ListNode* find_middle(ListNode* head){

ListNode* quick = head;
ListNode* slow = head;

while(quick -> next && quick -> next -> next){

slow = slow -> next;
quick = quick -> next -> next;
}

return slow;
}

ListNode* reverse(ListNode* head){

ListNode* cur = head;
ListNode* pre = NULL;

while(cur){

ListNode* next_node = cur -> next;
cur -> next = pre;

pre = cur;
cur = next_node;
}

return pre;
}

bool isPalindrome(ListNode* head) {

if(!head || !head -> next) //0或1个结点直接返回true
return true;

ListNode* middle = find_middle(head);

ListNode* l2 = middle -> next;
middle -> next = NULL; //断开前后两半

l2 = reverse(l2);

while(head && l2){

if(head -> val != l2 -> val)
return false;

head = head -> next;
l2 = l2 -> next;
}

if(l2)
return false;
if(head && head -> next) //只可能多出0或1个结点
return false;

return true;
}
};
CATALOG
  1. 1. 题目简介:
  2. 2. 思路:
  3. 3. 代码如下: