力扣打卡——反转链表、回文链表判断 题解

目录

[206. 反转链表 - 力扣(LeetCode)](#206. 反转链表 - 力扣(LeetCode))

[234. 回文链表 - 力扣(LeetCode)](#234. 回文链表 - 力扣(LeetCode))


206. 反转链表 - 力扣(LeetCode)

思路:

就是用双指针进行反转

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode current=head;
        ListNode pre=null;
        ListNode tmp;
        while(current!=null){
            tmp=current.next;
            current.next=pre;
            
            pre=current;
            current=tmp;
        }
        return pre;
    }
}

234. 回文链表 - 力扣(LeetCode)

思路:

快慢指针找中点 slow 走一步,fast 走两步,最后 slow 指向链表中点。

反转后半段 链表slow.next 开始的后半段反转。

前后两段逐一比较前半段从头开始,后半段从反转后的头开始,一一对比。

复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head ==null || head.next==null) return true;
        
        //根据快慢指针找到中点
        ListNode slow=head;
        ListNode fast=head;
        while(fast.next!=null && fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        //反转后半段部分
        ListNode right=reverse(slow.next);
        ListNode left=head;
        //进行比对
        while(right!=null && left!=null){
            if(right.val!=left.val) {
                return false;
            }
            right=right.next;
            left=left.next;
        }
        return true;
        
    }
    public ListNode reverse(ListNode head){
        ListNode pre=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode tmp=cur.next;
            cur.next=pre;
            pre=cur;
            cur=tmp;
        }
        return pre;
    }
}
相关推荐
W23035765736 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
minji...7 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
语戚8 小时前
力扣 968. 监控二叉树 —— 贪心 & 树形 DP 双解法递归 + 非递归全解(Java 实现)
java·算法·leetcode·贪心算法·动态规划·力扣·
skywalker_118 小时前
力扣hot100-7(接雨水),8(无重复字符的最长子串)
算法·leetcode·职场和发展
bIo7lyA8v9 小时前
算法稳定性分析中的输入扰动建模的技术9
算法
CoderCodingNo9 小时前
【GESP】C++三级真题 luogu-B4499, [GESP202603 三级] 二进制回文串
数据结构·c++·算法
sinat_286945199 小时前
AI Coding 时代的 TDD:从理念到工程落地
人工智能·深度学习·算法·tdd
炽烈小老头10 小时前
【 每天学习一点算法 2026/04/12】x 的平方根
学习·算法
ASKED_201910 小时前
从排序到生成:腾讯广告算法大赛 2025 baseline解读
人工智能·算法