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

};
相关推荐
肆忆_14 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星18 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode