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;
    }

};
相关推荐
Dave_Young1 小时前
上位机开发过程中的设计模式体会(1):工厂方法模式、单例模式和生成器模式
c++·设计模式
old_power1 小时前
在 Windows 系统下配置 VSCode + CMake + Ninja 进行 C++ 或 Qt 开发
c++·windows·vscode·cmake·ninja
UP_Continue2 小时前
C++--string的模拟实现
java·开发语言·c++
CodeWithMe2 小时前
【C/C++】高效的位操作
c语言·c++
newki2 小时前
学习笔记,关于NDK/JNI的简介与实战
android·c++·app
四谷夕雨3 小时前
C++八股 —— 单例模式
c++
委婉待续4 小时前
Qt的学习(二)
c++·qt
nenchoumi31195 小时前
UE5 学习系列(一)创建一个游戏工程
c++·学习·游戏·ue5
温宇飞5 小时前
C++ 作用域和标识符查找规则详解
c++
随意0235 小时前
STL 1 容器
开发语言·c++