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 分钟前
day04(11.2)——leetcode面试经典150
算法·leetcode
仟濹22 分钟前
「经典图形题」集合 | C/C++
c语言·开发语言·c++
乙己4071 小时前
设计模式——单例模式(singleton)
java·c++·单例模式·设计模式
嵌入式小李.man1 小时前
linux中多路复用IO:select、poll和epoll
linux·c++
郝学胜-神的一滴2 小时前
QAxios研发笔记(二):在Qt环境下基于Promise风格简化Http的Post请求
开发语言·c++·笔记·qt·网络协议·程序人生·http
晨非辰2 小时前
《数据结构风云》:二叉树遍历的底层思维>递归与迭代的双重视角
数据结构·c++·人工智能·算法·链表·面试
Tisfy2 小时前
LeetCode 3217.从链表中移除在数组中存在的节点:哈希表(一次遍历)
leetcode·链表·散列表
小白菜又菜3 小时前
Leetcode 495. Teemo Attacking
算法·leetcode·职场和发展
Yupureki4 小时前
从零开始的C++学习生活 17:异常和智能指针
c语言·数据结构·c++·学习·visual studio
.柒宇.8 小时前
力扣hot100----15.三数之和(java版)
java·数据结构·算法·leetcode