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;
    }
}
相关推荐
风筝在晴天搁浅19 分钟前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
千寻girling26 分钟前
《 Git 详细教程 》
前端·后端·面试
MATLAB代码顾问2 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天2 小时前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap2 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿2 小时前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6673 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
Cosolar3 小时前
一文吃透 LangChain&LangGraph:设计理念、框架结构与内部组件全拆解
人工智能·面试·架构
消失的旧时光-19433 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
智者知已应修善业3 小时前
【51单片机不用数组动态数码管显示字符和LED流水灯】2023-10-3
c++·经验分享·笔记·算法·51单片机