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;
    }
}
相关推荐
xieliyu.11 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
一条小锦吕*11 小时前
基于Spring Boot + 数据可视化 + 协同过滤算法的推荐系统设计与实现(源码+论文+部署全讲解)
spring boot·算法·信息可视化
綝~12 小时前
爬虫数据采集工程师岗位面试题
爬虫·面试·请求
如竟没有火炬13 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
8Qi813 小时前
LeetCode 1143 & 718:最长公共子序列 / 最长重复子数组
算法·leetcode·职场和发展·动态规划
绿算技术14 小时前
万卡推理集群存储选型分析:从核心架构到应用视角
大数据·科技·算法·架构
想吃火锅100515 小时前
【leetcode】1.两数之和js版
javascript·算法·leetcode
net3m3315 小时前
一阶软件低通滤波器算法
人工智能·算法
乐观的山里娃16 小时前
【反八股 01】HashMap 的设计参数是怎么来的
面试