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;
    }
}
相关推荐
I_LPL4 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱5 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
发现一只大呆瓜5 小时前
React-彻底搞懂 Redux:从单向数据流到 useReducer 的终极抉择
前端·react.js·面试
WolfGang0073215 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
零雲6 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
uzong6 小时前
Skill 被广泛应用,到底什么是 Skill,今天详细介绍一下
人工智能·后端·面试
发现一只大呆瓜6 小时前
React-路由监听 / 跳转 / 守卫全攻略(附实战代码)
前端·react.js·面试
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you7 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018727 小时前
C++中的状态模式
开发语言·c++·算法