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

};
相关推荐
秦少游在淮海43 分钟前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5441 小时前
cpp自学 day2(—>运算符)
开发语言·c++
虾球xz1 小时前
CppCon 2015 学习:CLANG/C2 for Windows
开发语言·c++·windows·学习
CodeWithMe2 小时前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
全栈凯哥2 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥2 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu2 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
愈努力俞幸运3 小时前
c++ 头文件
开发语言·c++
~山有木兮3 小时前
C++设计模式 - 单例模式
c++·单例模式·设计模式
蒟蒻小袁3 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先