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

目录

[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;
    }
}
相关推荐
luj_17688 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
geats人山人海11 小时前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
漂流瓶jz11 小时前
UVA-12627 奇怪的气球膨胀 题解答案代码 算法竞赛入门经典第二版
算法·图论·递归·aoapc·算法竞赛入门经典·uva·12627
jarvisuni12 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
kobesdu12 小时前
流形上的优化:SO(3)与SE(3)的广义加减法在FAST-LIO中如何简化状态估计
人工智能·算法·fastlio
白狐_79812 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
乐观勇敢坚强的老彭12 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶12 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶12 小时前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
图灵机z13 小时前
【算法提高课】AcWing 1027. 方格取数 长期攻克提高课-day3(3/219)
算法