234. 回文链表 请判断一个链表是否为回文链表。
示例 1: 输入: 1->2 输出: false
示例 2: 输入: 1->2->2->1 输出: true
/**
1 定义2个指针,head tail
2. 递归遍历tail链表
3. 通过
head++ 链表前进, 递归特点:从上到下
这个是子递归完在函数内部修改的,然后当前递归在使用
head已经发生改变)
tail -- 链表倒退,
递归特点 回溯,利用函数栈跟踪轨获取最后节点。
tail没有改变
判断是否回文 tail ==head
4.如果是继续,如果不是返回false
//执行用时: 20 ms, 在Palindrome Linked List的C++提交中击败了42.09% 的用户
**/
class Solution {
public:
bool isPalindrome(ListNode* head) {
//这2个参数意义不一样一个指针,一个指针的引用
return isPalindrome(head,head);
}
bool isPalindrome(ListNode* tail,ListNode* &head)
{
if(NULL==tail)
{
return true;
}
//从上到下不做任何原始比较,直到结束。返回true
bool flag=isPalindrome(tail->next,head);
if (false ==flag)
{
return false;
} //最外层比较
if (tail->val !=head->val)
{
return false;
}
//最里层比较,head是引用,修改的指针本身
head =head->next;
return flag;
}
};
因为采用递归
执行用时: 20 ms, 在Palindrome Linked List的C++提交中击败了42.09% 的用户
空间: o(n) 时间:o(n)
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有