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;
    }
}
相关推荐
生态学者3 分钟前
香港理工大学Nature Communications:沿海塑料际古菌组特征及生态影响
大数据·人工智能·算法·r语言·微信公众平台
ocean21036 分钟前
2025-2026年计算机网络面试高频知识点洞察
计算机网络·面试·职场和发展·https·tcp·面试真题·秋招春招
圣保罗的大教堂7 分钟前
leetcode 3904. 最小稳定下标 II 中等
leetcode
ly-2725320 分钟前
IEEE PDF eXpress终稿检测踩坑记录:PDF图片字体未嵌入与LaTeX参考文献编译异常解决方法
服务器·人工智能·算法
代码不停28 分钟前
子序列问题
java·算法
黎阳之光43 分钟前
AI黑光相机|赋能低空全域感知,筑牢低空经济全天候视觉防线
人工智能·物联网·算法·安全·数字孪生
手写码匠1 小时前
华为云Flexus+DeepSeek征文|DeepSeek R1 推理优化实战:让复杂任务的回答又快又稳
人工智能·深度学习·算法·aigc
Cabbage_acmer1 小时前
cf训练-gpt
算法
wenyq71 小时前
LeetCode 438. Find All Anagrams in a String
算法·leetcode
LB21121 小时前
力扣102 198 70 55
数据结构·算法·leetcode