Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in O(n) time and O(1) space?

这道题让我们判断一个链表是否为回文链表,LeetCode 中关于回文串的题共有六道,除了这道,其他的五道为 Palindrome NumberValidate PalindromePalindrome PartitioningPalindrome Partitioning II 和 Longest Palindromic Substring。链表比字符串难的地方就在于不能通过坐标来直接访问,而只能从头开始遍历到某个位置。那么根据回文串的特点,我们需要比较对应位置的值是否相等,一个非常直接的思路就是先按顺序把所有的结点值都存入到一个栈 stack 里,然后利用栈的后入先出的特性,就可以按顺序从末尾取出结点值了,此时再从头遍历一遍链表,就可以比较回文的对应位置了,若不同直接返回 false 即可,参见代码如下:

解法一:

class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *cur = head;
stack<int> st;
while (cur) {
st.push(cur->val);
cur = cur->next;
}
while (head) {
int t = st.top(); st.pop();
if (head->val != t) return false;
head = head->next;
}
return true;
}
};

我们也可以用迭代的形式来实现,此时需要使用一个全局变量结点 cur,先初始化为头结点,可以有两种写法,一种写在函数外面的全局变量,或者是在递归函数的参数中加上引用,也表示使用的是全局变量。然后对头结点调用递归函数,在递归函数中,首先判空,若为空则直接返回 true,否则就对下一个结点调用递归函数,若递归函数返回 true 且同时再当前结点值跟 cur 的结点值相同的话,就表明是回文串,否则就不是,注意每次 cur 需要指向下一个结点,参见代码如下:

解法二:

class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *cur = head;
return helper(head, cur);
}
bool helper(ListNode* node, ListNode*& cur) {
if (!node) return true;
bool res = helper(node->next, cur) && (cur->val == node->val);
cur = cur->next;
return res;
}
};

其实上面的两种解法重复比较一些结点,因为只要前半个链表和后半个链表对应值相等,就是一个回文链表,而并不需要再比较一遍后半个链表,所以我们可以找到链表的中点,这个可以用快慢指针来实现,使用方法可以参见之前的两篇 Convert Sorted List to Binary Search Tree 和 Reorder List,使用快慢指针找中点的原理是 fast 和 slow 两个指针,每次快指针走两步,慢指针走一步,等快指针走完时,慢指针的位置就是中点。我们还需要用栈,每次慢指针走一步,都把值存入栈中,等到达中点时,链表的前半段都存入栈中了,由于栈的后进先出的性质,就可以和后半段链表按照回文对应的顺序比较了,参见代码如下:

解法三:

class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
stack<int> st{{head->val}};
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
st.push(slow->val);
}
if (!fast->next) st.pop();
while (slow->next) {
slow = slow->next;
int tmp = st.top(); st.pop();
if (tmp != slow->val) return false;
}
return true;
}
};

这道题的 Follow up 让我们用 O(1) 的空间,那就是说我们不能使用 stack 了,那么如何代替 stack 的作用呢,用 stack 的目的是为了利用其后进先出的特点,好倒着取出前半段的元素。那么现在不用 stack 了,如何倒着取元素呢。我们可以在找到中点后,将后半段的链表翻转一下,这样我们就可以按照回文的顺序比较了,参见代码如下:

解法四:

class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *last = slow->next, *pre = head;
while (last->next) {
ListNode *tmp = last->next;
last->next = tmp->next;
tmp->next = slow->next;
slow->next = tmp;
}
while (slow->next) {
slow = slow->next;
if (pre->val != slow->val) return false;
pre = pre->next;
}
return true;
}
};

Githbu 同步地址:

https://github.com/grandyang/leetcode/issues/234

类似题目:

Palindrome Number

Validate Palindrome

Palindrome Partitioning

Palindrome Partitioning II

Longest Palindromic Substring

Reverse Linked List

参考资料:

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

https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand

https://leetcode.com/problems/palindrome-linked-list/discuss/148220/Javathe-clear-method-with-stack

https://leetcode.com/problems/palindrome-linked-list/discuss/64490/My-easy-understand-C%2B%2B-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Palindrome Linked List 回文链表的更多相关文章

  1. [CareerCup] 2.7 Palindrome Linked List 回文链表

    2.7 Implement a function to check if a linked list is a palindrome. LeetCode上的原题,参见我之前的博客Palindrome ...

  2. [LeetCode] 234. Palindrome Linked List 回文链表

    Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ...

  3. 234 Palindrome Linked List 回文链表

    请检查一个链表是否为回文链表. 进阶:你能在 O(n) 的时间和 O(1) 的额外空间中做到吗? 详见:https://leetcode.com/problems/palindrome-linked- ...

  4. lintcode 中等题:Palindrome Linked List 回文链表

    题目 回文链表 设计一种方式检查一个链表是否为回文链表. 样例 1->2->1 就是一个回文链表. 挑战 O(n)的时间和O(1)的额外空间. 解题 法一: 再定义一个链表,存放链表反转的 ...

  5. [LeetCode] Palindrome Number 验证回文数字

    Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. S ...

  6. [LeetCode] Palindrome Permutation II 回文全排列之二

    Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...

  7. [LeetCode] Palindrome Partitioning 拆分回文串

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  8. [Leetcode] palindrome partition ii 回文分区

    Given a string s, partition s such that every substring of the partition is a palindrome. Return the ...

  9. [Leetcode] Palindrome number 判断回文数

    Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. S ...

随机推荐

  1. Chrome调试中的奇技淫巧

    网上有关Chrome调试的文章一搜一大堆,本文主要记录一下自己平时经常用并且又比较冷门的一些技巧. 打开Chrome调试工具 1.打开控制台的情况下,长按页面的“刷新”按钮可以选择按何种方式刷新(有正 ...

  2. 关于css清除浮动,解决内容溢出的问题

    以前在布局的时候总会遇到这样的问题,比如我想让整体的内容居中,所以会这样写, .main-content{ width:960px:height:300px;margin:0px auto; } 然后 ...

  3. 利用Python进行数据分析(5) NumPy基础: ndarray索引和切片

    概念理解 索引即通过一个无符号整数值获取数组里的值. 切片即对数组里某个片段的描述. 一维数组 一维数组的索引 一维数组的索引和Python列表的功能类似: 一维数组的切片 一维数组的切片语法格式为a ...

  4. scikit-learn一般实例之六:构建评估器之前进行缺失值填充

    本例将会展示对确实值进行填充能比简单的对样例中缺失值进行简单的丢弃能获得更好的结果.填充不一定能提升预测精度,所以请通过交叉验证进行检验.有时删除有缺失值的记录或使用标记符号会更有效. 缺失值可以被替 ...

  5. Elastic学习第一天遇到的问题以及添加的一些操作

    1.刚开始安装好了之后,启动之后, 报错: ERROR: max file descriptors [] ] 需要设置max file descriptors为65536,出现这个是因为普通的用户是1 ...

  6. STL: unordered_map 自定义键值使用

    使用Windows下 RECT 类型做unordered_map 键值 1. Hash 函数 计算自定义类型的hash值. struct hash_RECT { size_t operator()(c ...

  7. html5+jqueryMobile编写App推广注册页

    html5+jqueryMobile的组合可以直接开发web版的app,所以用到我当前app中的推广注册页的编写是很恰当的,其实只要你熟悉html4+jquery的组合开发,那么html5+jquer ...

  8. WEB项目会话集群的三种办法

    web集群时session同步的3种方法 在做了web集群后,你肯定会首先考虑session同步问题,因为通过负载均衡后,同一个IP访问同一个页面会被分配到不同的服务器上, 如果session不同步的 ...

  9. jdk源码分析PriorityQueue

    一.结构 PriorityQueue是一个堆,任意节点都是以它为根节点的子树中的最小节点 堆的逻辑结构是完全二叉树状的,存储结构是用数组去存储的,随机访问性好.最小堆的根元素是最小的,最大堆的根元素是 ...

  10. (转)ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务 的解决方法

    早上同事用PL/SQL连接虚拟机中的Oracle数据库,发现又报了"ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务"错误,帮其解决后,发现很多人遇到过这样的问 ...