LeetCode 234 - 回文链表 C++ 实现

leetcode 题目:https://leetcode.cn/problems/palindrome-linked-list/description/

1. 题目:

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表

如果是,返回 true ;否则,返回 false 。

示例 1:

输入:head = [1,2,2,1]

输出:true

示例 2:

输入:head = [1,2]

输出:false

提示:链表中节点数目在范围[1, 105] 内

0 <= Node.val <= 9

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

2. 解题思路:

中等难度的符合题目:

思路:寻找链表的中间位置 + 翻转链表

寻找链表的中间位置是LeetCode 题目 806; 视频讲解

翻转链表 是 Leetcode 题目 234; 视频讲解

3. C++ 实现

C++ 实现:

C++ 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {

        if(!head || !head->next)
            return true;

        ListNode* slow = head;
        ListNode* fast = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }

        // 如果链表是奇数个数,则把正中的归到左边
        if(fast != NULL) slow = slow->next;

        slow = reverse(slow);
        fast = head;
        while(slow && fast){
            if(slow->val != fast->val){
                return false;
            }
            fast = fast->next;
            slow = slow->next;
        }

        return true;
    }
	
	//  翻转链表实现
    ListNode* reverse(ListNode* head){
        if(!head)
            return NULL;

        ListNode* pre_node = NULL;
        ListNode* cur_node = head;
        while(cur_node != NULL){

            ListNode* next = cur_node->next;
            cur_node->next = pre_node;

            pre_node = cur_node;
            cur_node = next;
        }

        return pre_node;
    }

};
相关推荐
颖川守一1 小时前
C++c6-类和对象-封装-设计案例2-点和圆的关系
开发语言·c++
·白小白1 小时前
力扣(LeetCode) ——100. 相同的树(C语言)
c语言·算法·leetcode
charlee441 小时前
将std容器的正向迭代器转换成反向迭代器
c++
ankleless2 小时前
数据结构(03)——线性表(顺序存储和链式存储)
数据结构·考研·链表·顺序表·线性表
arbboter2 小时前
【C++20】新特性探秘:提升现代C++开发效率的利器
c++·c++20·新特性·span·结构化绑定·初始化变量·模板参数推导
zc.ovo2 小时前
图论水题4
c++·算法·图论
眠りたいです3 小时前
Qt音频播放器项目实践:文件过滤、元数据提取与动态歌词显示实现
c++·qt·ui·音视频·媒体·qt5·mime
墩墩同学3 小时前
【LeetCode题解】LeetCode 74. 搜索二维矩阵
算法·leetcode·二分查找
汤永红3 小时前
week2-[循环嵌套]数位和为m倍数的数
c++·算法·信睡奥赛
1白天的黑夜15 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和