day40(12.21)——leetcode面试经典150

19. 删除链表的倒数第 N 个结点

19. 删除链表的倒数第N个结点

题目:

题解:

java 复制代码
/**
 * 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 removeNthFromEnd(ListNode head, int n) {
        if(head == null) {
            return head;
        }
        ListNode cur = head;
        int length = 0;
        while(cur != null) {
            cur = cur.next;
            length++;
        }
        n = length-n;
        cur = head;
        if(n==0) {
            return head.next;
        }
        length = 0;
        while(cur != null) {
            length++;
            if(length==n) {
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return head;
    }
}

82. 删除排序链表中的重复元素 II

82. 删除排序链表的重复元素Ⅱ

题目:

题解:

java 复制代码
/**
 * 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 deleteDuplicates(ListNode head) {
        if(head == null) {
            return head;
        }
        //指向当前元素
        ListNode cur = head;
        //创建虚拟头节点
        ListNode drum = new ListNode();
        drum.next = head;
        //用一个pre指向当前元素的前面一个指针
        ListNode pre = drum;
        while(cur.next != null) {
            if(pre.next.val != cur.next.val) {
                cur = cur.next;
                pre = pre.next;
            }
            else {
                while(cur.next != null && pre.next.val == cur.next.val) {
                    cur = cur.next;
                }
                cur = cur.next;
                pre.next = cur;
            }
            //这里进行判断cur!=null是因为cur可能经过else之后变成null,cur.next就会报空指针异常
            //如果把这个放在while里面进行判断,那么下面的出了while以后的if,else就会报错,因为进行了cur=cur.next
            if(cur == null) {
                return drum.next;
            }
        }
        if(pre.next == cur) {
            cur = cur.next;
        }
        else {
            pre.next = cur.next;
        }
        return drum.next;
    }
}
相关推荐
AI小老六1 小时前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
云技纵横1 小时前
@Transactional 到底要不要加 rollbackFor?一次数据不一致事故讲清楚
后端·面试
Moment1 小时前
牛逼,NextJs 从 16.3 开始全面拥抱 Agent Native 🥰🥰🥰
前端·后端·面试
胡萝卜术2 小时前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
胡萝卜术2 小时前
从暴力到Z字形消元:力扣240「搜索二维矩阵II」的降维打击之路
前端·javascript·面试
Asize2 小时前
初识DFS 与 BFS:递归、队列与图遍历
算法
罗西的思考16 小时前
机器人 / 强化学习】HIL-SERL:人类在环驱动的具身智能进化框架
人工智能·算法·机器学习
美团技术团队19 小时前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法
洛卡卡了20 小时前
我们在用 AI 写代码时,为什么建议要好好维护 AGENTS.md 呢?
面试·agent·claude
PBitW20 小时前
GPT训练我的第三天,明白了应该咋说满分回答!😕😕😕
前端·javascript·面试